2014-02-23 106 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));