问题描述
给定以下 SWIG 接口定义:
Given the following SWIG interface definition:
%module example
%include "arrays_csharp.i"
%apply int INOUT[] {int *x}
struct mystruct
{
int *x;
}
SWIG 生成以下内容(来自 mystruct.cs 的片段):
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
}
}
这会导致 VS2010 产生以下两个错误:
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.
我根据http://www.swig.org/开发了界面Doc1.3/CSharp.html#CSharp_arrays_pinvoke_default_array_marshalling ,只讨论函数而不讨论结构.结构成员的接口定义应该不同吗?
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?
推荐答案
可能是因为内存中的大小/布局未知(这对 int/double/等等...).您可以使用结构向量代替吗?通过简单地包含 std_vector.i
和相关的类型映射,我在传递结构向量或自定义对象方面没有问题,例如:
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>;
这篇关于如何使用 SWIG 类型映射使用 P/Invoke 将结构成员从 C++ 编组到 C#?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!