简体   繁体   中英

c# marshaling dynamic-length string

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM