将C ++中的struct指针编组到C#中的数组

时间:2016-01-24 23:16:48

标签: c# c++ pointers struct marshalling

我有以下C ++结构:

typedef struct Point
{
    int x;
    int y;
} Point;


typedef struct IMTResult
{
    int    numberOfPoints;
    Point* vect_intima;
    Point* vect_media;
    Point* vect_adventitia;
} IMTResult;

其中numberOfPointsPoint

的每个指针的长度

这个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始终会生成xy等于-1的向量 。我也尝试编组作为每个这些向量的属性失败。 有谁可以帮助我?

1 个答案:

答案 0 :(得分:-1)

事实上,根本没有问题。代码绝对正确。谢谢!