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

时间:2014-11-17 16:04:52

标签: 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"

我得到以下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()电话中发生。

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:3)

您可以使用%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的所有变体,您还需要做更多的工作。

答案 1 :(得分:-1)

20.8.7 of the SWIG docs节展示了如何使用typemap(cscode)来扩展生成的类。

相关问题