How do I use SWIG typemaps to marshall structure members from C++ to C# using P/Invoke?

不想你离开。 提交于 2020-12-31 01:42:00

问题


Given the following SWIG interface definition:

%module example

%include "arrays_csharp.i"
%apply int INOUT[] {int *x}

struct mystruct
{
        int *x;
}

SWIG produces the following (snippet from mystruct.cs):

  public int[] x {
    set {
      examplePINVOKE.mystruct_x_set(swigCPtr, value);
    } 
    get {
      IntPtr cPtr = examplePINVOKE.mystruct_x_get(swigCPtr); // Error 1
      SWIGTYPE_p_int ret = (cPtr == IntPtr.Zero) ? null : new SWIGTYPE_p_int(cPtr, false);
      return ret; //Error 2
    } 
  }

This causes VS2010 to produce the following two errors:

Error   1   Cannot implicitly convert type 'int[]' to 'System.IntPtr'   
Error   2   Cannot implicitly convert type 'LibLinear.SWIG.SWIGTYPE_p_int' to 'int[]'

at the areas marked in the above code snippet.

I developed the interface according to http://www.swig.org/Doc1.3/CSharp.html#CSharp_arrays_pinvoke_default_array_marshalling , which only talks about functions but not structures. Should the interface definition for structure members be different?


回答1:


It might be that it can't handle an array of structs because of the unknown size/layout in memory (which is not a problem for int/double/etc...). Is it possible for you to use a vector of structs instead? I've had no problems passing vectors of structs or custom objects by simply including std_vector.i and relevant typemaps, eg:

%include "std_vector.i"

%typemap(MyClassVec) std::vector<MyClass>;


来源:https://stackoverflow.com/questions/7330641/how-do-i-use-swig-typemaps-to-marshall-structure-members-from-c-to-c-sharp-usi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!