![](/img/trans.png)
[英]P/Invoke marshaling and unmarshalling 2D array, structure and pointers between C# and unmanaged DLL
[英]Passing structure containing an array of structures between C and C# (DLL and P invoke)
我有一個復雜的結構C dll我真的是C#的新手:
typedef struct {
int a;
int b;
} simple_struct;
typedef struct {
int d;
int e;
simple_struct f[20];
short g;
simple_struct h[20];
short i;
} complex_struct;
問題是我無法使用這種結構連接我的C#應用程序!
在DLL中有一個函數GetData(complex_struct * myStruct),我應該從C#中調用它,所以我創建了:
[StructLayout(LayoutKind.Sequential, Pack = 1)]
unsafe struct simple_struct {
public int a;
public int b;
} ;
[StructLayout(LayoutKind.Sequential, Pack = 1)]
unsafe struct complex_struct {
public int d;
public int e;
public simple_struct[] f;
public short g;
public simple_struct[] h;
public short i;
} ;
但問題是,當我將complex_struct作為GetData的參數傳遞時,所有字段都從我身上填充,但不是我的兩個simple_struct數組(我的意思是f和h)! 他們的價值觀無效!
謝謝,有人可以幫助我
嗨,謝謝你的回復,
我已經像你說的那樣做了,但是當我調用GetData時仍然有另一個問題,進程崩潰而沒有任何消息(一種異常):
這是我的急劇代碼:namespace dll_test_import_c_sharp {class Program {[StructLayout(LayoutKind.Sequential,Pack = 1)] struct simple_struct {public int a; public int b; };
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct complex_struct {
public int d;
public int e;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
public simple_struct[] f;
public short g;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
public simple_struct[] h;
public short i;
} ;
[DllImport("test_dll.dll", CharSet = CharSet.Unicode)]
static extern int GetData(ref complex_struct a);
static void Main(string[] args)
{
complex_struct a = new complex_struct();
GetData(ref a);
return;
}
}
}
我已經做了很多printf我GetData並且所有這些都執行得很好,好像'return'指令崩潰了!
我試圖通過ref或out調用GetData,它們都不起作用......
嗨,謝謝你的回復,
我已經像你說的那樣做了,但是當我調用GetData時仍然有另一個問題,進程崩潰而沒有任何消息(一種異常):
這是我的急劇代碼:namespace dll_test_import_c_sharp {class Program {[StructLayout(LayoutKind.Sequential,Pack = 1)] struct simple_struct {public int a; public int b; };
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct complex_struct {
public int d;
public int e;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
public simple_struct[] f;
public short g;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
public simple_struct[] h;
public short i;
} ;
[DllImport("test_dll.dll", CharSet = CharSet.Unicode)]
static extern int GetData(ref complex_struct a);
static void Main(string[] args)
{
complex_struct a = new complex_struct();
GetData(ref a);
return;
}
}
}
我已經做了很多printf我GetData並且所有這些都執行得很好,好像'return'指令崩潰了!
我試圖通過ref或out調用GetData,它們都不起作用......
您需要更改struct
上的數組定義以指定它是按值/內聯數組
[StructLayout(LayoutKind.Sequential, Pack = 1)]
unsafe struct complex_struct {
public int d;
public int e;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
public simple_struct[] f;
public short g;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
public simple_struct[] h;
public short i;
} ;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.