添加剂结构的大小

时间:2014-02-23 22:18:32

标签: c# hook marshalling

我想复制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;

您对此结构的正确尺寸以及我做错了吗?

非常感谢你的时间。

1 个答案:

答案 0 :(得分:2)

我很久以前就解决了这个问题,所以我只想在这里发帖也可以帮助其他人。

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