如何使用 SWIG 类型映射来编组来自 C++ 的结构成员使用 P/Invoke 转换为 C#?
给定以下 SWIG 接口定义:
%module example
%include "arrays_csharp.i"
%apply int INOUT[] {int *x}
struct mystruct
{
int *x;
}
SWIG 产生以下内容(来自 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 产生以下两个错误:
Error 1 Cannot implicitly convert type 'int[]' to 'System.IntPtr'
Error 2 Cannot implicitly convert type 'LibLinear.SWIG.SWIGTYPE_p_int' to 'int[]'
在上述代码片段中标记的区域。
我根据 http://www.swig.org/Doc1.3 开发了界面/CSharp.html#CSharp_arrays_pinvoke_default_array_marshalling ,仅讨论函数而不讨论结构。结构成员的接口定义是否应该不同?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于内存中未知的大小/布局,它可能无法处理结构数组(这对于 int/double/etc 来说不是问题)。您可以使用结构向量来代替吗?通过简单地包含
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: