【问题标题】:Get byte array byte Marshal获取字节数组字节元帅
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-19
    • 1970-01-01
    • 2019-07-23
    相关资源
    最近更新 更多