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)开发者_StackOverflow社区]
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);
}
}
精彩评论