时间:2019-03-17 标签:c#marshalingdynamic-lengthstring
我有一个具有动态长度的结构:
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct PktAck
{
public Int32 code;
[MarshalAs(UnmanagedType.LPStr)]
public string text;
}
当我通过以下代码将 bytes[] 转换为 struct 时:
GCHandle handle = GCHandle.Alloc(bytes_array, GCHandleType.Pinned);
result_struct = (PktAck)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(PktAck));
handle.Free();
我有一个错误,因为结构的大小小于 bytes[] 的大小,并且“字符串文本”是指向字符串的指针...
我如何使用动态字符串? 或者我只能使用这样的东西:
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1000)]
upd: c struct
struct PktAck
{
int code;
char* text;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您想将此结构编组到 PInvoke 调用中,那么我将使用
Marshal
类来分配字符串。If you are wanting to marshal this struct into a PInvoke call then I would use the
Marshal
class to allocate the string.