如何在C#中编组具有未知长度字符串字段的结构

我得到一个字节数组,我需要将它解组为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, 我还发现这个链接有同样的问题未解决: 将二进制数据加载到结构中 谢谢你们, 奥菲尔     
已邀请:
我会用
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位填充字段。谁生成了这个字节流? 但是确切的格式对于这个策略来说并不是很重要,因为你可以将ѭ3改变为
ReadInt16
,重新排序它们,无论如何,使它工作。 我不喜欢序列化程序属性。这是因为它将您的内部数据结构与交换方式相结合。如果您需要支持多个版本的dataformat,这会中断。     
这不是一个答案(但是)是一个问题/评论,有大量的反馈代码。你如何解释你的字节数组?分解。
[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();
}
    

要回复问题请先登录注册