c++ 如何序列化protobuf枚举值用于纯文本/ prototxt存储?

yc0p9oo0  于 2023-01-22  发布在  其他
关注(0)|答案(1)|浏览(213)

我可以使用google::protobuf::TextFormat::Print成功地将其他字段序列化为ASCII,但是我的枚举没有显示。我做错了什么?
代码如下:
main.cpp

#include <iostream>
#include <filesystem>
#include <fcntl.h>
#include <unistd.h>

#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/text_format.h>

#include "example.pb.h"

bool pb_SaveToFile( const std::filesystem::path      File,
                      const google::protobuf::Message &Message )
{
    int fd = open ( File.string ( ).c_str ( ), O_WRONLY | O_CREAT | O_TRUNC, 0666 );

    if ( fd == - 1 )
    {
        return false;
    }

    google::protobuf::io::FileOutputStream * output =
        new google::protobuf::io::FileOutputStream ( fd );

    bool                                     success =
        google::protobuf::TextFormat::Print ( Message, output );

    delete output;

    close ( fd );

    return success;
}


int main(int argc, char *argv[])
{

    std::filesystem::path fullPath = "saved.prototxt";

    pbtest::PbTestMessage tm;

    // Timestamp
    auto ts = tm.mutable_timestamptest();

    ts->set_seconds(time(NULL));
    ts->set_nanos(0);

    // Enum
    tm.set_enumtest(::pbtest::enumTestValues::ENUM_ZERO);

    // String
    tm.set_stringtest("string test!");

    // Save it
    pb_SaveToFile(fullPath, tm);

    std::cout << "Done!" << std::endl;
    return 0;
}

example.proto

syntax = "proto3";

import "google/protobuf/timestamp.proto";

package pbtest;

enum enumTestValues {
    ENUM_ZERO = 0;
    ENUM_ONE = 1;
  }

message PbTestMessage {

    google.protobuf.Timestamp timestampTest = 1;

    enumTestValues enumTest = 2;

    string stringTest = 3;
}

CMakeLists.txt

cmake_minimum_required(VERSION 2.8.9)

project (protobuf-example)

find_package(Protobuf REQUIRED)

include_directories(${Protobuf_INCLUDE_DIRS})
include_directories(${CMAKE_CURRENT_BINARY_DIR})
protobuf_generate_cpp(PROTO_SRCS PROTO_HDRS example.proto)

add_executable(protobuf-example main.cpp ${PROTO_SRCS} ${PROTO_HDRS})
target_link_libraries(protobuf-example ${Protobuf_LIBRARIES})

target_compile_features(protobuf-example PRIVATE cxx_std_17)

如果运行此命令,保存到saved.prototxt的输出如下所示:

timestampTest {
  seconds: 1673886921
}
stringTest: "string test!"

如何将枚举保存到文件中?

aelbi1ox

aelbi1ox1#

正如注解中的@Igor Tandetnik所回答的,这实际上是一个特性,如果你试图打印枚举的默认值,它会被忽略。
将我的代码更改为:

tm.set_enumtest(::pbtest::enumTestValues::ENUM_ONE);

将生成以下输出:

timestampTest {
  seconds: 1673892775
}
enumTest: ENUM_ONE
stringTest: "string test!"

相关问题