2016-11-23 127 views
-1

我有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); 
    } 
+0

为什么'XgTunWrap.encapsulation(出unmPont'的_out_参数很奇怪,因为你只是在分配/分配mem。 –

+0

' - >>> catch(Exception ex){throw;} <<< - '是无用的。将它移除,因为finally总是被调用。 –

+0

也'Marshal.Copy(msg,0,unmPont , - > msg.Length < - );'**应**'Marshal.Copy(MSG,0,unmPont, - > lenghtAr < - );' –

回答

0

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