使用StructLayout.Sequential創建託管版本的非託管結構(請確保按照相同的順序)。然後,您應該能夠通過它就像你把它傳遞給任何管理功能(例如,驗證(MYSTRUCT [] pStructs)
例如,假設我們的本地函數有這個原型:
extern "C" {
STRUCTINTEROPTEST_API int fnStructInteropTest(MYSTRUCT *pStructs, int nItems);
}
和本地MYSTRUCT定義如下:
struct MYSTRUCT
{
int a;
int b;
char c;
};
然後在C#中,您定義的結構的一個託管版本如下:
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public struct MYSTRUCT
{
public int a;
public int b;
public byte c;
}
和託管原型如下:
[System.Runtime.InteropServices.DllImportAttribute("StructInteropTest.dll", EntryPoint = "fnStructInteropTest")]
public static extern int fnStructInteropTest(MYSTRUCT[] pStructs, int nItems);
然後,您可以調用函數傳遞MYSTRUCT結構數組如下:
static void Main(string[] args)
{
MYSTRUCT[] structs = new MYSTRUCT[5];
for (int i = 0; i < structs.Length; i++)
{
structs[i].a = i;
structs[i].b = i + structs.Length;
structs[i].c = (byte)(60 + i);
}
NativeMethods.fnStructInteropTest(structs, structs.Length);
Console.ReadLine();
}