简体   繁体   English

字节数组到struct

[英]Byte array to struct

I'm having trouble converting the string parts of the byte array. 我在转换字节数组的字符串部分时遇到问题。

My struct looks like this: 我的结构看起来像这样:

[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct Message
{
    public int id;

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)]
    public string text;
}

Creation of test byte array: 创建测试字节数组:

private static byte[] CreateMessageByteArray()
{
    int id = 69;
    byte[] intBytes = BitConverter.GetBytes(id);

    string text = "test";
    byte[] stringBytes = GetBytes(text);

    IEnumerable<byte> rv = intBytes.Concat(stringBytes);

    return rv.ToArray();
}

Method to convert my bytearray to a struct: 将我的bytearray转换为结构的方法:

static T ByteArrayToStructure<T>(byte[] bytes) where T : struct
{
    var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
    var result = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
    handle.Free();
    return result;
}

When I call ByteArrayToStructure with the result from CreateMessageByteArray() I get a struct with an id=60 and text="t". 当我使用CreateMessageByteArray()的结果调用ByteArrayToStructure ,我得到一个id = 60和text =“t”的结构。

Why don't I get the whole string eg "test" ? 为什么我没有得到整个字符串,例如“test”?

Edit: This is the code I forgot to pase: 编辑:这是我忘记编码的代码:

    static byte[] GetBytes(string str)
    {
        byte[] bytes = new byte[str.Length * sizeof(char)];
        System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
        return bytes;
    }

The problem is at this line: 问题出在这一行:

byte[] stringBytes = GetBytes(text);

How are you converting the string to a byte array? 你是如何将字符串转换为字节数组的? You are probably using a Unicode encoding, which will store each character as two bytes, and because your string is in the ASCII set, every other byte will be zero: 您可能正在使用Unicode编码,它将每个字符存储为两个字节,并且因为您的字符串是ASCII集,所以每隔一个字节将为零:

byte[] stringBytes = new UnicodeEncoding().GetBytes(text);
// will give you { 't', '\0', 'e', '\0', 's', '\0', 't', '\0' }

These zeroes mislead the marshalling mechanism into assuming they are terminal characters and so the string ends just after the 't' . 这些零错误地将编组机制误认为它们是终端字符,因此字符串在't'之后结束。

Instead, you can use an ASCII encoding (which stores one byte per character): 相反,您可以使用ASCII编码(每个字符存储一个字节):

byte[] stringBytes = new ASCIIEncoding().GetBytes(text);
// will give you { 't', 'e', 's', 't' }
// but will lose non-ASCII character information

Or you can use a UTF8 encoding (which is variable length): 或者您可以使用UTF8编码(可变长度):

byte[] stringBytes = new UTF8Encoding().GetBytes(text);
// will give you { 't', 'e', 's', 't' }    
// and retain non-ASCII character information, but it's somewhat
// trickier to rebuild the string correctly in case of non-ASCII
// information present

除了其他两个答案之外,如果您希望text字段中的字符串始终为Unicode,则可以在[StructLayout]属性中包含CharSet = CharSet.Unicode

Maybe GetBytes method doesn't work as you expect. 也许GetBytes方法不能按预期工作。 This linqpad works fine for me: 这个linqpad对我来说很好:

void Main()
{
    var result = ByteArrayToStructure<Message>(CreateMessageByteArray());
    result.Dump();
}

[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct Message
{
    public int id;

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)]
    public string text;
}

private static byte[] CreateMessageByteArray()
{
    int id = 69;
    byte[] intBytes = BitConverter.GetBytes(id);

    string text = "test";
    byte[] stringBytes = Encoding.UTF8.GetBytes(text);

    IEnumerable<byte> rv = intBytes.Concat(stringBytes);

    return rv.ToArray();
}

static T ByteArrayToStructure<T>(byte[] bytes) where T : struct
{
    var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
    var result = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
    handle.Free();
    return result;
}

Output: 输出:

id    69 
text  test 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM