我无法转换字节数组的字符串部分。字节数组结构
我的结构是这样的:
[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 = 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;
}
当我打电话ByteArrayToStructure
从CreateMessageByteArray()
的结果我得到一个id = 60和text =“t”的结构。
为什么我不能得到整个字符串,例如“测试”?
编辑: 这是我忘了填写Flash代码:
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;
}
我猜想为MarshalAs属性添加“CharSet = CharSet.Unicode”也可以。 – cubrr