我在C#中有一個函數,它將結構數組傳遞給用C++編寫的DLL。該結構是一組整數,當我讀出DLL中的數據時,所有的值都可以正常顯示。但是,如果我嘗試從C++寫入元素,那麼當我嘗試讀取C#時,這些值永遠不會顯示出來。將值賦給C++結構中的值爲從C#傳遞的結構時出現問題#
C#
[StructLayout(LayoutKind.Sequential)]
struct Box
{
public int x;
public int y;
public int width;
public int height;
}
[StructLayout(LayoutKind.Sequential)]
struct Spot
{
public int x;
public int y;
}
static void TestCvStructs()
{
int len = 100;
Box[] r = new Box[len];
Spot[] p = new Spot[len];
for (int i = 0; i < len; i++)
{
r[i].x = i*10;
r[i].y = i * 200;
r[i].width = r[i].x * 10;
r[i].height = r[i].y * 100 + r[i].x * 5;
p[i].x = i * 8;
p[i].y = i * 12;
}
PassCvStructs(len, r, p);
for (int i = 0; i < len; i++)
{
Console.WriteLine("Point/x:{0} Boxes/x{1}", p[i].x, r[i].x);
}
}
[DllImport(dll)]
private static extern int PassSomeStructs(int count, Box[] boxes, Spot[] points);
C++
typedef struct Box
{
int x;
int y;
int width;
int height;
} Box;
typedef struct Spot
{
int x;
int y;
} Spot;
CPPDLL_API int PassSomeStructs(int arrayLength, Box *boxes, Spot *points)
{
for(int i = 0; i < arrayLength; ++i)
{
printf("Group:%i\n", i);
printf("Rect - x:%i y:%i width:%i length:%i\n", boxes[i].x, boxes[i].y, boxes[i].width, boxes[i].height);
printf("Point - x:%i y:%i\n", points[i].x, points[i].y);
printf("\n");
points[i].x = 3;
boxes[i].x = 1;
}
return 0;
}
從行爲看,它看起來像它的傳遞參考。當我嘗試使用ref時,我在C++端獲得了瘋狂的值,就像這些值實際上是指針一樣。如果我將接收類型改爲指向指針的指針,我會得到一個內存訪問異常:(我打算將所有內容都打包到一個int數組中,並且通過這個,導致這個「Magic」讓我感到困惑。 – QueueHammer