2014-02-23 59 views
0

我想复制addrinfo结构(只需复制它的所有字节),但是当挂钩时,我的更改导致主机应用程序中的内存损坏。addrinfo结构的大小

我的代码也很简单:

byte[] addressInfoBytes = new byte[32]; 
Marshal.Copy(addressInfoAddress, addressInfoBytes, 0, addressInfoBytes.Length); 
newAddressInfoAddress = GCHandle.Alloc(addressInfoBytes, GCHandleType.Pinned).AddrOfPinnedObject(); 

我认为这是因为32是不是这个结构的正确尺寸。 我计算基于这个定义在MSDN上这个号码:

typedef struct addrinfo { 
    int    ai_flags; 
    int    ai_family; 
    int    ai_socktype; 
    int    ai_protocol; 
    size_t   ai_addrlen; 
    char   *ai_canonname; 
    struct sockaddr *ai_addr; 
    struct addrinfo *ai_next; 
} ADDRINFOA, *PADDRINFOA; 

你有关于这个结构的正确大小和我做什么不正确任何想法?

非常感谢您的时间。

+0

此结构用于什么?你确定你没有试图访问已经在托管对等项目中提供的本地土地吗? –

回答

1

我很久以前就解决了这个问题,所以我只是觉得在这里发布它可能会帮助其他人。

using System.Net; 
    using System.Net.Sockets; 

    [StructLayout(LayoutKind.Sequential)] 
    internal struct AddressInfo 
    { 
     internal AddressInfoHints Flags; 

     internal AddressFamily Family; 

     internal SocketType SocketType; 

     internal ProtocolFamily Protocol; 

     internal int AddressLen; 

     internal IntPtr CanonName; // sbyte Array 

     internal IntPtr Address; // byte Array 

     internal IntPtr Next; // Next Element In AddressInfo Array 

     [Flags] 
     internal enum AddressInfoHints 
     { 
      None = 0, 
      Passive = 0x01, 
      Canonname = 0x02, 
      Numerichost = 0x04, 
      All = 0x0100, 
      Addrconfig = 0x0400, 
      V4Mapped = 0x0800, 
      NonAuthoritative = 0x04000, 
      Secure = 0x08000, 
      ReturnPreferredNames = 0x010000, 
      Fqdn = 0x00020000, 
      Fileserver = 0x00040000, 
     } 
    } 

    AddressInfo addressInfo = (AddressInfo)Marshal.PtrToStructure(handle, typeof(AddressInfo));