C# 结构到字节数组[SafeArrayTypeMismatchException]
在字节数组中复制结构时出错 System.Runtime.InteropServices.SafeArrayTypeMismatchException 结构:C# 结构到字节数组[SafeArrayTypeMismatchException],c#,marshalling,C#,Marshalling,在字节数组中复制结构时出错 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; p
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;
}
intsizeee是全局变量,调整结构中所有数据的大小
此行出错: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;
}
byte[]获取字节(T str),其中T:struct
{
int size=Marshal.SizeOf(str);
字节[]arr=新字节[大小];
IntPtr ptr=Marshal.AllocHGlobal(大小);
Marshal.StructureToPtr(str,ptr,true);
封送处理副本(ptr、arr、0、大小);
弗里赫全球元帅(ptr);
返回arr;
}
你应该考虑把异常文本放在你的文章中而不是标题。