struct to byte array [SafeArrayTypeMismatchException]
本文关键字:SafeArrayTypeMismatchException array to byte struct | 更新日期: 2023-09-27 18:18:42
复制字节数组结构时出错。
System.Runtime.InteropServices.SafeArrayTypeMismatchException
结构:
public struct fbody
{
public float left;
public float right;
public float bottom;
public float top;
public char[] regname;
public int index;
public char[] weather;
public char[] sound;
public byte[] regcolor;
public byte endstr;
};
在字节数组中记录的函数:
private byte[] StructToByteArray(object _oStruct)
{
byte[] mem = new byte[sizeee];
IntPtr hmem = Marshal.AllocHGlobal(sizeee);
Marshal.StructureToPtr(_oStruct, hmem, false);
Marshal.Copy(hmem, mem, 0, mem.Length);
return mem;
}
int sizeee是全局变量,对结构体中的所有数据进行大小调整。
本行错误:Marshal。StructureToPtr(_oStruct, hmem, false);
你可以这样写:
byte[] getBytes<T>(T str) where T:struct
{
int size = Marshal.SizeOf(str);
byte[] arr = new byte[size];
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(str, ptr, true);
Marshal.Copy(ptr, arr, 0, size);
Marshal.FreeHGlobal(ptr);
return arr;
}