我得到一个字节数组,我需要将它解组为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
}
字节数组如下所示: 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,
我还发现这个链接有同样的问题未解决: loading binary data into a structure
谢谢大家, 奥菲尔
答案 0 :(得分:3)
我会用BinaryReader
来做。这将遵循这些方针:
Foo ReadFoo(Byte[] bytes)
{
Foo foo = new Foo();
BinaryReader reader = new BinaryReader(new MemoryStream(bytes));
foo.ID = reader.ReadUInt32();
int userNameCharCount = reader.ReadUInt32();
foo.UserName = new String(reader.ReadChars(userNameCharCount));
int fullNameCharCount = reader.ReadUInt32();
foo.FullName = new String(reader.ReadChars(fullNameCharCount));
return foo;
}
请注意,这不会直接用于您提供的字节数组示例。 char计数和ID字段不是标准的小端或bigendian顺序。可能是字段是16位,并且它们前面有16位填充字段。谁生成了这个字节流?
但确切的格式对于此策略并不重要,因为您可以将ReadInt32
更改为ReadInt16
,重新排序,无论如何,以使其正常工作。
我不喜欢序列化程序属性。这是因为它将您的内部数据结构与交换方式相结合。如果您需要支持多个版本的dataformat,这会中断。
答案 1 :(得分: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();
}