Pinvoke结构
问题描述:
我具有以下结构定义:
#ifndef struct_emxArray_real_T
#define struct_emxArray_real_T
struct emxArray_real_T
{
real_T *data;
int32_T *size;
int32_T allocatedSize;
int32_T numDimensions;
boolean_T canFreeData;
};
#endif /*struct_emxArray_real_T*/
,并希望通过PInvoke在C#中使用它.该结构旨在表示一个矩阵.任何C#结构代码将不胜感激.谢谢!
and would like to use it in C# via PInvoke. The struct is meant to represent a matrix. Any C# struct code would be very much appreciated. Thanks!
有人在此处进行了尝试:
[StructLayout(LayoutKind.Sequential, Size = 1)]
public unsafe struct mytype
{
public double* data;
public int* size;
public int allocatedSize;
public int numDimensions;
public bool canFreeData;
}
但没有使其正常工作.
答
C#结构不支持指针类型.
C# structs do not support pointer types.
相反,必须将指针移植为IntPtr
.您可以使用Marshal
类来解析指针.
Instead, pointers must be ported as IntPtr
; you can use the Marshal
class to resolve the pointer.
因此,您应该编写类似
[StructLayout(LayoutKind.Sequential)]
public unsafe struct mytype
{
public IntPtr data;
public IntPtr size;
public int allocatedSize;
public int numDimensions;
public bool canFreeData;
}
检查您的boolean_T
类型的大小;您可能需要使用[MarshalAs(...)]
属性指定正确的大小.
Check what size your boolean_T
type is; you may need to use the [MarshalAs(...)]
attribute to specify the correct size.