-1

在字节数组中复制结构时出错。

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

4

1 回答 1

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;
}
于 2013-06-17T20:21:30.007 回答