如何将二进制文件读入 QString 类型的 protobuf?

How can I read a binary file into a protobuf that is of the type QString?

所以我有一个二进制文件,它的名称作为 const QString& filename 传递到我的函数中,我正在尝试将它读入 ProtoBuf。我试过示例 ParseFromArray(file.data(), file.size()) 但它不起作用并且大小为 1.

正确的做法是什么?谢谢!

这是我的相关代码片段:

bool open(const QString& filename)
{
    myProject::protobuf::Example _example;

    // need to copy contents from file to _example
}

您需要先使用 QFile and then read its contents using its inherited method readAll() which will return a QByteArray. Then, use QByteArray::data() and QByteArray::size() 打开文件以传递给 ParseFromArray(const void* data, int size)。您还需要在需要时处理错误。

这是一个例子:

bool open( const QString& filename )
{
    QFile file { filename };
    if ( !file.open( QIODevice::ReadOnly ) ) return false;

    const auto data = file.readAll();
    if ( data.isEmpty() ) return false;

    if ( !ParseFromArray( data.data(), data.size() ) ) return false;

    // successful parsing: process here...

    return true;
}