struct to byte数组[SafeArrayTypeMismatchException]

时间:2013-06-17 19:39:53

标签: 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;
    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);

1 个答案:

答案 0 :(得分:0)

你可以这样:

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;
}