2016-01-24 69 views
-1

我有以下C++結構:編組在C++結構的一個指針在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 。我也嘗試將這些向量中的每一個都歸屬爲屬性失敗。 任何人都可以幫助我嗎?

+0

您是否檢查過指針以查看它們是否合理?如果結構中的指針偏移量錯誤,則數據將無效......您是否確認了「IMTResult」的結構大小在C#和C++之間是一致的?大多數這些問題都是由於包裝或類型大小差異造成的結構成員不對齊。 32位或64位指針,打包等等都起作用。 – Corey

回答

-1

事實上,根本沒有問題。代碼是絕對正確的。謝謝!