我有一个在dll中的C++导出函数:
int MyMethod(ulong pid, MyStruct* struct);
MyStruct类描述如下:
class MyStruct
{
public:
uchar nVersion;
uchar nModuleType;
uchar nMachine64;
uchar nReserved;
ulong data1;
ulong data2;
ulong data3;
};
我将尝试将这个函数导入到我的C#代码中,代码如下:
[DllImport("mydll.dll", EntryPoint = "#24")]
private static extern int _MyMethod(long pid, ref MyStruct struct);
C#中的类:
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
stuct MyStruct
{
public byte nVersion;
public byte nModuleType;
public byte nMachine64;
public byte nReserved;
public ulong data1;
public ulong data2;
public ulong data3;
}
我遇到了System.AccessViolationException
异常:
MyStruct struct = new MyStruct();
_MyMethod(4728, ref struct);
有什么问题吗?
更新:
System.Runtime.InteropServices.Marshal.SizeOf(struct)
返回32。为什么?我原以为应该是4 * 1 + 8 * 3 = 28。