c++ - ProtocolBuffer,SerializeToArray() 上的 abort()

标签 c++ protocol-buffers

我从我通常使用的原型(prototype)类创建了一个 ProtocolBuffer 对象,我需要将它序列化。现在,我获取该对象并对其调用 SerializeToArray(),如下所示:

int size = messageObject.ByteSize();
void* buffer = malloc(size);
messageObject.SerializeToArray(buffer, size);

据我所知这没有问题,因为对象中有数据(我通过在 Serialize 行之前中断来检查它)。

然而,当该方法调用时,它会触发一个我一无所知的 abort() 。 我不知道它可能是什么。该对象中包含的唯一数据是一个“类型”枚举器(我可以将其设置为该对象中使用的数据类型,因为它可以包含不同种类的消息)并且它包含一个可重复的消息对象类型。

message MessageID 
{
    enum Type { LOGINDATA = 1; PLAYERDATA = 2; WORLDDATA = 3; }

    // Identifies which field is filled in.
    required Type type = 1;

    // One of the following will be filled in.
    repeated PlayerData playerData = 2;
    optional WorldData worldData = 3;
    optional LoginData loginData = 10;
}

这是基本信息。因此,在这种情况下,Type 是 2,代表 PLAYERDATA。此外,playerData 是使用 PlayerData 类型的单个对象设置的。

感谢您的帮助。

最佳答案

任何时候 protobuf 库中止(同样,它应该只处于 Debug模式或在严重情况下),它会将有关问题的信息打印到控制台。如果您的应用没有控制台,您可以使用 google::protobuf::SetLogHandler 将信息定向到其他地方:

https://developers.google.com/protocol-buffers/docs/reference/cpp/google.protobuf.common#SetLogHandler.details

typedef void LogHandler(LogLevel level, const char* filename,
                        int line, const std::string& message);
LogHandler* SetLogHandler(LogHandler* new_func);

The protobuf library sometimes writes warning and error messages to stderr.

These messages are primarily useful for developers, but may also help end users figure out a problem. If you would prefer that these messages be sent somewhere other than stderr, call SetLogHandler() to set your own handler. This returns the old handler. Set the handler to NULL to ignore log messages (but see also LogSilencer, below).

Obviously, SetLogHandler is not thread-safe. You should only call it at initialization time, and probably not from library code. If you simply want to suppress log messages temporarily (e.g. because you have some code that tends to trigger them frequently and you know the warnings are not important to you), use the LogSilencer class below.

据我所知(仅适用于调试版本)的唯一中止原因是未设置某些必填字段。你说 type 字段已设置,那么 PlayerData 中必须有一个未设置的必填字段。

关于c++ - ProtocolBuffer,SerializeToArray() 上的 abort(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24894617/

相关文章:

java - 在 Java 和 C++ 应用程序中使用 protobuf 进行解析时出错

json - 如何在protobuf或grpc中使用json作为结构体成员?

android - gRPC 客户端 : error in compiled file (io. grpc.protobuf 不存在)

c++ - std::istream 上的 Windows IStream 接口(interface)

c++ - C/C++ 中的嵌套注释

c# - 将指针数组从 C++ 返回到 C#

c++ - std::future 作为返回类型的未定义行为?

c++ - catch 是否保证在抛出异常后执行?

python - 反序列化带有 header 和重复字段的流式 Protocol Buffer 消息

parsing - 在不知道.proto的情况下解析 Protocol Buffer