将代码添加到 SWIG 中自动生成的类

Add code to automatically generated class in SWIG

本文关键字:自动生成 SWIG 代码 添加      更新时间:2023-10-16

我正在尝试找到一种方法来添加代码来wig生成的函数。我已经使用类型图来扩展类,但在文档中找不到有关扩展特定函数的任何内容。

给定以下 swig 接口文件:

%module Test
%{
#include "example.h"
%}
%typemap(cscode) Example %{
    bool 64bit = SizeOf(typeof(System.IntPtr)) == 8;
    static string Path = 64bit ? "/...Path to 64 bit dll.../" : 
                                 "/...Path to 32 bit dll.../";
%}
%include "example.h"

我得到以下 C# 代码:

public class MyClass : global::System.IDisposable {
    ...
    bool 64bit = SizeOf(typeof(System.IntPtr)) == 8;
    static string Path = 64bit ? "/...Path to 64 bit dll.../" : 
                                 "/...Path to 32 bit dll.../";
    ...
    public static SomeObject Process(...) {     // Function defined in example.h
                                               <- I would like to add some code here.
        SomeObject ret = new SomeObject(...);
    }
    ...
}

我想向函数 Process 添加一些代码,此代码是对 SetDllDirectory(Path) 的调用,它根据平台类型加载正确的 dll。这需要在Process()调用中进行。

任何帮助将不胜感激!

您可以使用

%typemap(csout)生成所需的代码。不过这有点麻烦,你需要复制一些现有的SWIGTYPE(这是一个通用占位符)的字体图,可以在csharp.swg中找到

例如,给定一个头文件 example.h:

struct SomeObject {};
struct MyClass {
  static SomeObject test();
};

然后,您可以编写以下 SWIG 接口文件:

%module Test
%{
#include "example.h"
%}
%typemap(csout,excode=SWIGEXCODE) SomeObject {
    // Some extra stuff here
    $&csclassname ret = new $&csclassname($imcall, true);$excode
    return ret;
}
%include "example.h"

它产生:

public static SomeObject test() {
    // Some extra stuff here
    SomeObject ret = new SomeObject(TestPINVOKE.MyClass_test(), true);
    return ret;
}

如果你想为所有返回类型生成它,而不仅仅是返回 SomeObject 的东西,你将有更多的工作要做,因为 csout 的所有变体。

>SWIG 文档的第 20.8.7 节展示了如何使用 typemap(cscode) 来扩展生成的类。