任何结构到byte []并返回

时间:2015-09-03 21:10:39

标签: c#

说,有代码:

class Program
{
    static void Main(string[] args)
    {
        MYSTRUCT1 s = new MYSTRUCT1();
        s.a = 1; s.b = 2; s.c = 3;
        byte[] buffer = StructToByteArray(s);
        MYSTRUCT1 ss = new MYSTRUCT1();
        ByteArrayToAnyStruct(ss, buffer); 
    }

    struct MYSTRUCT1 { public int a; public int b; public int c; }
    struct MYSTRUCT2 { public int a; public string b; }

    static byte[] StructToByteArray(object s)
    {
        byte[] data = new byte[Marshal.SizeOf(s)];
        IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(s));
        Marshal.StructureToPtr(s, ptr, true);
        Marshal.Copy(ptr, data, 0, data.Length);
        Marshal.FreeHGlobal(ptr);
        return data;
    }
    static void ByteArrayToAnyStruct(object s, byte[] buffer)
    {
        IntPtr ptr = Marshal.AllocHGlobal(buffer.Length);
        Marshal.Copy(buffer, 0, ptr, buffer.Length);
        Marshal.PtrToStructure(ptr, s); <---- what's wrong with this structure?
        Marshal.FreeHGlobal(ptr);
    }
}

转换为缓冲区工作正常,但反向上升异常 在ByteArrayToAnyStruct中这个结构有什么问题?

2 个答案:

答案 0 :(得分:1)

做你想要的你需要使用重载方法调用来返回像这样的对象

替换

Marshal.PtrToStructure(ptr, s); //<---- what's wrong with this structure?

s = Marshal.PtrToStructure(ptr, s.GetType());

您还需要使用

更改主叫行
ByteArrayToAnyStruct(ref ss, buffer); 

和方法签名

static void ByteArrayToAnyStruct<T>(ref T s, byte[] buffer)  where T : struct

working fiddler example

答案 1 :(得分:0)

谢谢! Fredou!

你是 s = Marshal.PtrToStructure(ptr,s.GetType()); 我已改为:

class Program
{
    static void Main(string[] args)
    {
        MYSTRUCT1 s = new MYSTRUCT1();
        s.a = 1; s.b = 2; s.c = 3;
        byte[] buffer = StructToByteArray(s);
        MYSTRUCT1 ss = (MYSTRUCT1)ByteArrayToAnyStruct(typeof(MYSTRUCT1), buffer); 
    }

    struct MYSTRUCT1 { public int a; public int b; public int c; }
    struct MYSTRUCT2 { public int a; public string b; }

    static byte[] StructToByteArray(object s)
    {
        byte[] data = new byte[Marshal.SizeOf(s)];
        IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(s));
        Marshal.StructureToPtr(s, ptr, true);
        Marshal.Copy(ptr, data, 0, data.Length);
        return data;
    }
    public static object ByteArrayToAnyStruct(Type type, byte[] buffer)
    {
        IntPtr ptr = Marshal.AllocHGlobal(buffer.Length);
        Marshal.Copy(buffer, 0, ptr, buffer.Length);
        object o = Marshal.PtrToStructure(ptr, type);
        Marshal.FreeHGlobal(ptr);
        return o;
    }
}

会标记你的答案。