UE4 结构体序列化和反序列化

All of UE4’s Serialize functions are dual operation - they work on both readers and writers. If you call SerializeBin with a reader archive instead of a writer archive, it will deserialise for you:

TArray Storage;
UStruct* MyStruct = FMyStruct::StaticStruct();

FMyStruct Before;
FMemoryWriter ArWriter(Storage);
MyStruct->SerializeBin(ArWriter, &Before);

FMyStruct After;
FMemoryReader ArReader(Storage);
MyStruct->SerializeBin(ArReader, &After);

// Before and After should now be equal
Hope this helps,

Steve

发现UE里很多问题度娘根本无法解决,只能科学上网去解决

大致翻译一下 就是SerializeBin这个函数可以序列化,也可以反序列化,参数传FMemoryWriter就是序列化,传FMemoryReader就是反序列化

比如你有一个自定义的FInputMsg

则大致的序列化和反序列化函数如下

UNetHelper.h


UFUNCTION(BlueprintCallable)
		static TArray<uint8> SerializeUserInputToBinaryArray(FInputMsg inputMessage );

	UFUNCTION(BlueprintCallable)
		static FInputMsg UnSerializeBinaryArrayToUserI
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
结构体序列化反序列化是将结构体数据转换为字节流,以便在网络传输或存储中使用,然后再将字节流还原为原始结构体数据的过程。 在C++中,可以通过以下几种方式实现结构体序列化反序列化: 1. 使用二进制流进行序列化反序列化:可以使用std::ofstream和std::ifstream类来将结构体数据写入文件或从文件读取结构体数据。例如: ```cpp struct MyStruct { int a; float b; char c; }; void serialize(const MyStruct& data, const std::string& filename) { std::ofstream file(filename, std::ios::binary); file.write(reinterpret_cast<const char*>(&data), sizeof(MyStruct)); file.close(); } void deserialize(MyStruct& data, const std::string& filename) { std::ifstream file(filename, std::ios::binary); file.read(reinterpret_cast<char*>(&data), sizeof(MyStruct)); file.close(); } ``` 2. 使用JSON进行序列化反序列化:可以使用第三方库(如RapidJSON、nlohmann/json等)将结构体数据转换为JSON格式的字符串,然后再将JSON字符串转换回结构体数据。例如: ```cpp #include <iostream> #include <string> #include <nlohmann/json.hpp> struct MyStruct { int a; float b; char c; }; void serialize(const MyStruct& data, const std::string& filename) { nlohmann::json json_data; json_data["a"] = data.a; json_data["b"] = data.b; json_data["c"] = data.c; std::ofstream file(filename); file << json_data.dump(4); // 4为缩进级别 file.close(); } void deserialize(MyStruct& data, const std::string& filename) { std::ifstream file(filename); nlohmann::json json_data; file >> json_data; file.close(); data.a = json_data["a"]; data.b = json_data["b"]; data.c = json_data["c"]; } int main() { MyStruct original_data {42, 3.14f, 'A'}; serialize(original_data, "data.json"); MyStruct restored_data; deserialize(restored_data, "data.json"); std::cout << "Restored data: a = " << restored_data.a << ", b = " << restored_data.b << ", c = " << restored_data.c << std::endl; return 0; } ``` 以上是两种常见的结构体序列化反序列化的方式,具体选择哪种方式取决于你的需求和场景。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱我呦呦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值