【发布时间】:2016-03-18 08:43:05
【问题描述】:
我有一些带有结构描述和一些方法的 C++ dll:
struct MSG_STRUCT {
unsigned long dataSize;
unsigned char* data;
}
还有函数举例:
unsigned long ReadMsg( unsigned long msgId, MSG_STRUCT* readMsg)
{
readMsg->dataSize = someDataSize;
readMsg->data = someData;
}
所以我想从C#调用这个函数:
[StructLayout(LayoutKind.Sequential)]
struct MSG_STRUCT
{
UInt32 dataSize;
byte[] data;
}
[DllImport("mydll.dll")]
public static Int32 ReadMsg( UInt32 msgId, ref MSG_STRUCT readMsg);
所以我尝试调用 C# 函数,例如:
var readMsg = new MSG_STRUCT();
readMsg.data = new byte[4128];
Int32 res = ReadMsg( someMsgId, ref readMsg);
但我的数据并不正常。
我也尝试使用IntPrt 类型参数调用ReadMsg,但Marshal.PtrToStructure 有时给了我AccessViolationException。
我不知道如何将指向 MSG_STRUCT 的指针从 C# 传递到 C++ 并接收填充的结果 MSG_STRUCT.data
对我有用的最终解决方案:
我使用了 xanatos 提供的部分解决方案:
我为我的 DllImport 函数设置了CallingConvention = CallingConvention.Cdecl。
我发现我也需要改变:
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4128)]
public byte[] Data;
感谢大家的帮助
【问题讨论】:
-
"但我的数据并不正常。"你得到了什么,你期待什么?数据应该是字符串还是字节数组?
-
数据应该是字节数组。
标签: c# c++ marshalling