views:

41

answers:

1

i have a struct with dynamic length:

   [StructLayout(LayoutKind.Sequential, Pack = 1)]
   struct PktAck
   {
      public Int32 code;
      [MarshalAs(UnmanagedType.LPStr)]
      public string text;
   }

when i'm converting bytes[] to struct by this code:

GCHandle handle = GCHandle.Alloc(bytes_array, GCHandleType.Pinned);
result_struct = (PktAck)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(PktAck));
handle.Free();

i have a error, because size of struct less than size of bytes[] and "string text" is pointer to string...

how can i use dynamic strings? or i can use only something like this:

  [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1000)]

upd: c struct

   struct PktAck
   {
       int code;
       char* text;
   }
A: 

If you are wanting to marshal this struct into a PInvoke call then I would use the Marshal class to allocate the string.

struct PktAck
{
  public Int32 code;
  public IntPtr text;
}

public static void Main()
{
  var a = new PktAck();
  a.code = 314159;
  a.text = Marshal.StringToHGlobalAnsi("foo");
  try
  {
    SomePInvokeCall(a);
  }
  finally
  {
    Marshal.FreeHGlobal(a.text);
  }
}
Brian Gideon
i want to convert bytes array to this struct and struct to array back.i have a function that do it, but this function doesn't work on dynamic struct.
mitsky
Once you change the stuct to use an `IntPtr` instead of `string` then it will have a fixed size. The `Marshal.PtrToStructure` call should work after that.
Brian Gideon