views:

30

answers:

2

Hi,

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

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

leppie
Could you give an example? I'm not really experienced in WinAPI calls.
+1  A: 

Hi,

the problem was that the Servent-Struct is differen 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

};

True, but it doesn't explain the crash.
Hans Passant
@Hans Passant: Of course it does! The size is different due to packing.
leppie
Thanks, this was indeed the problem!