Ofi*_*fir 8 c# struct marshalling unmarshalling
我得到一个字节数组,我需要将它解组为C#struct.我知道结构的类型,它有一些字符串字段.字节数组中的字符串如下所示:两个第一个字节是字符串的长度,然后是字符串本身.我不知道琴弦的长度.我知道它的Unicode!
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public class User
{
int Id;//should be 1
String UserName;//should be OFIR
String FullName;//should be OFIR
}
Run Code Online (Sandbox Code Playgroud)
字节数组如下所示:00,00,01,00,00,00,08,00,4F,00,46,00,49,00,52,00,00,00,08,00,4F,00 ,46,00,49,00,52,00,
我还发现这个链接有同样的问题未解决: 将二进制数据加载到结构中
谢谢大家,Ofir
小智 0
这还不是答案,而是一个带有大量反馈代码的问题/评论。你如何解释你的字节数组?分解它。
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
struct Foo
{
public int id;
//[MarshalAs(UnmanagedType.BStr)]
//public string A;
//[MarshalAs(UnmanagedType.BStr)]
//public string B;
}
static void Main(string[] args)
{
byte[] bits = new byte[] {
0x00, 0x00,
0x01, 0x00,
0x00, 0x00,
0x08, 0x00, // Length prefix?
0x4F, 0x00, // Start OFIR?
0x46, 0x00,
0x49, 0x00,
0x52, 0x00,
0x00, 0x00,
0x08, 0x00, // Length prefix?
0x4F, 0x00, // Start OFIR?
0x46, 0x00,
0x49, 0x00,
0x52, 0x00 };
GCHandle pinnedPacket = GCHandle.Alloc(bits, GCHandleType.Pinned);
Foo msg = (Foo)Marshal.PtrToStructure(
pinnedPacket.AddrOfPinnedObject(),
typeof(Foo));
pinnedPacket.Free();
}
Run Code Online (Sandbox Code Playgroud)