任意到byte[]并返回的结构体

本文关键字:返回 结构体 byte 任意 | 更新日期: 2023-09-27 18:11:17

说,这里有代码:

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中的这个结构有什么问题?

任意到byte[]并返回的结构体

要做你想做的事情,你需要使用重载的方法调用,返回一个像这样的对象

代替

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

工作小提琴手示例

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

将标记你的答案