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

Tim*_*m B 6 c# c++ swig dllimport

我正在尝试找到一种方法来为swig生成的函数添加代码.我使用了类型映射来扩展类,但在文档中找不到有关扩展特定函数的任何内容.

给出以下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"
Run Code Online (Sandbox Code Playgroud)

我得到以下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(...);

    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

我想在函数Process中添加一些代码,这段代码是一个调用,SetDllDirectory(Path)根据平台类型加载正确的dll.这需要在Process()通话中发生.

任何帮助是极大的赞赏!

Fle*_*exo 4

您可以使用 生成您正在寻找的代码%typemap(csout)。不过,这有点麻烦,您需要复制 SWIGTYPE 的一些现有类型映射(这是一个通用占位符),可以在 csharp.swg 中找到

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

struct SomeObject {};

struct MyClass {
  static SomeObject test();
};
Run Code Online (Sandbox Code Playgroud)

然后您可以编写以下 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"
Run Code Online (Sandbox Code Playgroud)

其产生:

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

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