获取字节数组字节Marshal

时间:2016-11-23 13:02:35

标签: c# arrays marshalling

我有XgTunWrap.encapsulation()

UInt16 encapsulation(out IntPtr pkt, UInt32 src_ip, UInt32 dst_ip, UInt16 sport, UInt16 dport, UInt16 pktLen);

函数(C#中的C ++ dll),它接受字节数组指针并封装该字节数组并返回字节数组的长度。我正在尝试使用编组来获取封装的字节数组,但是会出现内存访问冲突错误。

在我的源代码下面给出了错误。有没有办法获得封装的字节数组?

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); 
     }

1 个答案:

答案 0 :(得分:0)

谢谢@Jeroen!我按照你的评论做了。我在out前删除了IntPtr。这是我的工作代码:

UInt16 encapsulation(IntPtr pkt,
                     UInt32 src_ip,
                     UInt32 dst_ip,
                     UInt16 sport, 
                     UInt16 dport, 
                     UInt16 pktLen);

和工作机构:

int lengthAr = Marshal.SizeOf(msg[0]) * msg.Length;
IntPtr unmPont = Marshal.AllocHGlobal(lengthAr);

try
{
    Marshal.Copy(msg, 0, unmPont, lengthAr);
    len = XgTunWrap.encapsulation(unmPont,
                                  m_pList.m_DeviceHoA.IpAddress,
                                  item.m_VptAliasHoA.IpAddress,
                                  (ushort)taPort,
                                  (ushort)taPort,
                                  (ushort)msg.Length);
    res = new byte[len];
    Marshal.Copy(unmPont, res, 0, (int)len);                                                                         
}
finally
{
    Marshal.FreeHGlobal(unmPont);
}