使用 StructLayout.Sequential 创建非托管结构的托管版本(确保以相同的顺序放置)。然后,您应该能够像将其传递给任何托管函数(例如,Validation(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();
}