【发布时间】:2012-10-10 07:10:24
【问题描述】:
我在 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
【问题讨论】:
-
它与“unsafe”关键字无关,它只是一个标准的marshal问题......
-
@user287107 你是对的,我把这个问题从答案的上下文中拿出来了。
-
顺便说一句,我曾经为 Delphi 编写过相同的代码来使用 c++ dll - 它确实有效。所以dll不会有问题。
-
大小不同,因为有padding。编译器会将结构大小增加到一个方便的数字。
-
c++ 做同样的事情吗?我想也许这就是问题
标签: c# c++ marshalling unmanaged