Problembär
Problembär

Reputation: 171

AccessViolationException when calling Marshal.PtrToStructure

I'm getting an AccessViolationExcpetion by calling Marshal.PtrToStructure(intPtr, typeof(Servent)). Any ideas what I have done wrong? I tried this on 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;
  }

Upvotes: 3

Views: 1699

Answers (2)

Problembär
Problembär

Reputation: 171

The problem was that the Servent struct is different on 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
};

Upvotes: 4

leppie
leppie

Reputation: 117250

You probably need to specify how the string fields are laid out, else marshalling will fail to determine the correct size for the type.

Upvotes: 0

Related Questions