我有一個非託管代碼和C#UI的C++ DLL。有一個從C++ DLL導入的函數,該函數採用write-by-me結構作爲參數。編組結構包含int和int []從C#到C++
編組結束(MyImage)從C#到C++後,我可以訪問其中的int []數組的內容,但內容是不同的。我不知道我在這裏失去了什麼,因爲我花了很長時間,並嘗試了一些技巧來解決這個問題(顯然不夠)。
MYIMAGE結構在C#:
[StructLayout(LayoutKind.Sequential)]
struct MyImage
{
public int width;
public int height;
public int[] bits; //these represent colors of image - 4 bytes for each pixel
}
MYIMAGE結構在C++:
struct MyImage
{
int width;
int height;
Color* bits; //typedef unsigned int Color;
MyImage(int w, int h)
{
bits = new Color[w*h];
}
Color GetPixel(int x, int y)
{
if (x or y out of image bounds) return UNDEFINED_COLOR;
return bits[y*width+x];
}
}
C#函數聲明與MYIMAGE作爲參數:
[DLLImport("G_DLL.dll")]
public static extern void DisplayImageInPolygon(Point[] p, int n, MyImage texture,
int tex_x0, int tex_y0);
C++實現
DLLEXPORT void __stdcall DisplayImageInPolygon(Point *p, int n, MyImage img,
int imgx0, int imgy0)
{
//And below they have improper values (i don't know where they come from)
Color test1 = img.GetPixel(0,0);
Color test2 = img.GetPixel(1,0);
}
因此,在調試問題時,我注意到C++結構中的MyImage.bits數組包含不同的數據。
我該如何解決?
是否有可能創建一個IntPtr int []數組沒有不安全的代碼?這個結構只有一個存在的目的 - >將圖像傳遞給C++層,在那裏我可以處理它。你是說我應該在IntPtr中傳遞整個結構? –
在這種情況下,我不會在C#中聲明結構。只需在傳遞數據的本地代碼中調用一個函數,並創建本地結構。 –
你說什麼爲我工作。還有1個問題:當我把它看作是正確的,當作爲函數參數傳遞時,int []數組被整理爲int *而沒有問題,並且當數組作爲int []傳遞給結構時,這不起作用?難道我們不能強制程序在結構內對待這個數組,就好像它將被作爲參數傳遞給函數一樣嗎? –