将结构指针封送到 C# 中的数组C++

本文关键字:数组 C++ 结构 指针 | 更新日期: 2023-09-27 18:31:38

我有以下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总是导致一个向量,其中xy等于 -1.我还尝试将这些向量中的每一个封为属性,但没有成功。谁能帮我?

将结构指针封送到 C# 中的数组C++

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