结构体与字节流的相互转换

从别处找的,备忘
        public static Byte[] StructToBytes(Object structure)
        {

            Int32 size = Marshal.SizeOf(structure);
            Console.WriteLine(size);
            IntPtr buffer = Marshal.AllocHGlobal(size);
            try
            {
                Marshal.StructureToPtr(structure, buffer, false);
                Byte[] bytes = new Byte[size];
                Marshal.Copy(buffer, bytes, 0, size);
                return bytes;
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);
            }
        }
        public static Object BytesToStruct(Byte[] bytes, Type strcutType)
        {
            Int32 size = Marshal.SizeOf(strcutType);
            IntPtr buffer = Marshal.AllocHGlobal(size);
            try
            {
                Marshal.Copy(bytes, 0, buffer, size);
                return Marshal.PtrToStructure(buffer, strcutType);
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);
            }
        }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将一个复杂结构体转换字节流,你可以使用序列化的方式。序列化是将数据结构转换字节流的过程,以便在不同的系统或平台之间进行传输或存储。 在 C++ 中,你可以使用库来实现结构体的序列化,例如 Google 的 Protocol Buffers、Boost 库中的序列化机制等。下面以 Google 的 Protocol Buffers 为例,演示如何进行结构体的序列化。 首先,你需要定义一个 .proto 文件来描述你的数据结构。例如,假设你有一个学生结构体,包含学生的姓名、年龄和学号: ```proto syntax = "proto3"; message Student { string name = 1; int32 age = 2; int32 student_id = 3; } ``` 接下来,你需要使用 Protocol Buffers 的编译器将 .proto 文件编译为对应的 C++ 类。假设你将生成的类命名为 StudentMessage。 然后,在你的 C++ 代码中,你可以使用生成的类来创建一个学生对象,并将其序列化为字节流: ```cpp #include "student_message.pb.h" #include <fstream> int main() { // 创建一个学生对象 StudentMessage::Student student; student.set_name("Alice"); student.set_age(18); student.set_student_id(12345); // 将学生对象序列化为字节流 std::string serialized_data; student.SerializeToString(&serialized_data); // 将字节流写入文件 std::ofstream file("student.bin", std::ios::binary); file.write(serialized_data.c_str(), serialized_data.size()); file.close(); return 0; } ``` 在上述示例中,我们创建了一个 Student 对象,并设置了学生的姓名、年龄和学号。然后,使用 Student 对象的 SerializeToString() 函数将其序列化为字节流,并将字节流写入文件 "student.bin"。 当你想要从字节流中反序列化恢复结构体时,你可以使用相应的反序列化函数进行操作。 希望这个示例能够帮助你理解如何使用序列化来将复杂结构体转换字节流。如果还有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值