无法在 C++ 平台中使用 Protocol Buffer 回读序列化数据

Cannot read back serialized data using protocol buffer in C++ platform

我刚开始使用protocol buffer并尝试做一个最小的例子来写入和读回数据。但是我没有读回序列化数据。

我用来制作示例的资源

1, 2, 3.

我的方法

生成序列化数据的结构和代码

.
├── CMakeLists.txt
├── lib
│   └── libproto_library.so # creted after the compilation
├── proto
│   └── message.proto
├── README.md
├── run_project.sh
└── src
    └── main.cpp

  • Points to be noted
    • I have compiled the project using cmake. Ignored the cmake file not to make the post messy. If needed, I can provide.
    • build folder is not shown in the structure. Generated header files by protoc complers are resided there.

message.proto

syntax = "proto3";
package message;
message Sensor {
  int32 humidity = 1;
}

main.cpp

#include <fstream>
#include <iostream>
#include "message.pb.h"

using namespace std;
int main(int argc, char const *argv[])
{
  message::Sensor sensor;
  sensor.set_humidity(68);

  std::fstream ofs("../bin/message.data", std::ios_base::out | std::ios_base::binary);
  sensor.SerializeToOstream(&ofs);

  return 0;
}

构建项目后,我使用了生成的message.pb.hmessage.datalibproto_library.so

反序列化数据的结构和代码

.
├── CMakeLists.txt
├── include
│   └── message.pb.h
├── lib
│   └── libproto_library.so
├── read_back_proto.sh
└── src
    ├── main.cpp
    └── message.data

main.cpp

#include <fstream>
#include <iostream>
#include <string>
#include "message.pb.h"

int main()
{
    std::fstream ifs ("message.data", std::ios_base::out | std::ios_base::binary);
    message::Sensor sensor;
    sensor.ParseFromIstream(&ifs);

    int32_t read_humidity = sensor.humidity();

    std::cout << "humidity : " << read_humidity << std::endl;

    return 0;
}

编译这个项目后,生成的可执行文件为我提供了 humidity 的值是 ZERO 而我期望它是 68.

正在寻找取回正确值的建议。

真是圈了个小问题。 message.data的路径错误。

  • 首先,我用 std::ios_base::out 打开文件。语法错误。虽然已经在问题中进行了编辑。
  • 可执行文件正在从 bin 目录执行
  • message.data 位于 bin 的上一层,在 src 目录中
  • 更正代码以读回序列化数据:
    #include <fstream>
    #include <iostream>
    #include <string>
    #include "message.pb.h"
    
    int main()
    {
        std::fstream ifs ("../src/message.data", std::ios_base::in | std::ios_base::binary);
        message::Sensor sensor;
        sensor.ParseFromIstream(&ifs);
    
        int32_t read_humidity = sensor.humidity();
    
        std::cout << "humidity : " << read_humidity << std::endl;
    
        return 0;
    }