我通过调用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;
  }

最佳答案

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

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

10-08 01:00