调用Marshal.PtrToStructure时出现AccessViolationException

时间:2010-09-01 12:52:25

标签: c# windows winapi marshalling

我通过调用Marshal.PtrToStructure(intPtr,typeof(Servent))来获取AccessViolationExcpetion。 我做错了什么想法?我在x64上试过这个。

    IntPtr intPtr = NativeMethods.GetServByName(name, "tcp");
     if (intPtr != IntPtr.Zero)
     {
        Servent servent = (Servent)Marshal.PtrToStructure(intPtr, typeof(Servent));
        result = System.Convert.ToInt32(IPAddress.NetworkToHostOrder(servent.s_port));
     }
     else
     {
        throw CreateWSAException();
     }


  [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
  internal struct Servent
  {
     public string s_name;
     public IntPtr s_aliases;
    public short s_port;
     public string s_proto;
  }

2 个答案:

答案 0 :(得分:4)

问题是Servent结构在x64上是不同的:

struct  servent {
        char    FAR * s_name;           /* official service name */
        char    FAR * FAR * s_aliases;  /* alias list */
#ifdef _WIN64
        char    FAR * s_proto;          /* protocol to use */
        short   s_port;                 /* port # */
#else
        short   s_port;                 /* port # */
        char    FAR * s_proto;          /* protocol to use */
#endif
};

答案 1 :(得分:0)

您可能需要指定字符串字段的布局方式,否则编组将无法确定该类型的正确大小。