【发布时间】:2016-11-23 13:02:34
【问题描述】:
我有 XgTunWrap.encapsulation()
UInt16 encapsulation(out IntPtr pkt, UInt32 src_ip, UInt32 dst_ip, UInt16 sport, UInt16 dport, UInt16 pktLen);
函数(C# 中的 C++ dll)接受字节数组指针并封装该字节数组并返回字节数组的长度。我正在尝试使用 Marshalling 获取封装的字节数组,但出现内存访问冲突错误。
在我的源代码下面,它给出了错误。有没有办法得到封装的字节数组?
int lenghtAr = Marshal.SizeOf(msg[0]) * msg.Length;
IntPtr unmPont = Marshal.AllocHGlobal(lenghtAr);
try
{
Marshal.Copy(msg, 0, unmPont, msg.Length);
len = XgTunWrap.encapsulation(out unmPont, m_pList.m_DeviceHoA.IpAddress, item.m_VptAliasHoA.IpAddress, (ushort)taPort, (ushort)taPort, (short)msg.Length);
res = new byte[len];
Marshal.Copy(unmPont, res, 0, (int)len);
}
catch (Exception ex)
{throw; }
finally
{
Marshal.FreeHGlobal(unmPont);
}
【问题讨论】:
-
为什么
XgTunWrap.encapsulation(out unmPont是一个out 参数?这很奇怪,因为您只是在上面分配/分配内存。 -
->>> catch (Exception ex) {throw; } <<<--没用。删除它,因为 finally 总是被调用。 -
还有
Marshal.Copy(msg, 0, unmPont, -> msg.Length <-);应该是Marshal.Copy(msg, 0, unmPont, -> lenghtAr <-);
标签: c# arrays marshalling