【发布时间】:2016-05-01 04:24:53
【问题描述】:
我有以下 C++ 结构:
typedef struct Point
{
int x;
int y;
} Point;
typedef struct IMTResult
{
int numberOfPoints;
Point* vect_intima;
Point* vect_media;
Point* vect_adventitia;
} IMTResult;
其中numberOfPoints是Point的每个指针的长度
还有这个 C++ 函数:
bool setSecondPoint( int x, int y, IMTResult* result );
如何在 C# 中编组这个 IMTResult 结构? 我试过了:
public struct IMTResult
{
public int numberOfPoints;
public IntPtr vect_intima;
public IntPtr vect_media;
public IntPtr vect_adventitia;
}
并尝试使用以下方法管理自己的三个向量:
[DllImport("MyDll.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern bool setSecondPoint(int x, int y, [MarshalAs(UnmanagedType.Struct)] ref IMTResult result);
public bool dllSetSecondPoint(int x, int y, ref IMTResult result)
{
bool res = setSecondPoint(x, y, ref result);
int structSize = Marshal.SizeOf(typeof(Point));
Point vect = new Point();
IntPtr ptr = result.vect_media;
for (int i = 0; i < result.numberOfPoints; i++)
{
Point vect = (Point) Marshal.PtrToStructure(ptr, typeof(Point));
ptr = (IntPtr)((int)ptr + structSize);
}
return res;
}
但vect 总是会产生一个向量,其中x 和y 等于-1
.我还尝试将这些向量中的每一个都编组为属性,但均未成功。
谁能帮帮我?
【问题讨论】:
-
你检查过这些指针是否合理吗?如果结构中的指针偏移量错误,则数据将无效...您确认
IMTResult的结构大小在C#和C++之间是一致的吗?大多数这些问题是由于结构成员的未对齐,因为包装或类型大小的差异。 32 位或 64 位指针、打包等都起作用。
标签: c# c++ pointers struct marshalling