欧美一区二区三区老妇人-欧美做爰猛烈大尺度电-99久久夜色精品国产亚洲a-亚洲福利视频一区二区

Protobuf 動(dòng)態(tài)加載 .pb 文件并操作 Message

之前寫了《Protobuf 動(dòng)態(tài)加載 .proto 文件并操作 Message》。除了直接讀取 .proto 文件之外,還有一種類似的方法。先把 .proto 文件編譯成 .pb 文件,再讀取 .pb 文件。這種方法雖然比直接讀取 .proto 多了一步,但是在運(yùn)行期加載更快。
仍然使用之前的的 .proto 文件作為示例。使用 protoc.proto 文件編譯為 .pb 文件。

網(wǎng)站建設(shè)哪家好,找成都創(chuàng)新互聯(lián)公司!專注于網(wǎng)頁設(shè)計(jì)、網(wǎng)站建設(shè)、微信開發(fā)、小程序制作、集團(tuán)企業(yè)網(wǎng)站建設(shè)等服務(wù)項(xiàng)目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了子洲免費(fèi)建站歡迎大家使用!

./3rdparty/bin/protoc -I./proto -oaddressbook.pb --include_imports ./proto/addressbook.proto

注意,這里有兩個(gè) .proto 文件,應(yīng)該選擇沒有被依賴的 .proto 文件作為參數(shù),并且添加 --include_imports 選項(xiàng)。這樣,所有 .proto 文件及其依賴的 .proto 文件都被編進(jìn)同一個(gè) .pb 文件。

#include <iostream>
#include <fstream>
#include <google/protobuf/dynamic_message.h>
#include <google/protobuf/util/json_util.h>
#include <google/protobuf/descriptor.pb.h>

using namespace google::protobuf;

int main()
{
    std::ifstream pb_file("./addressbook.pb", std::ios::binary);
    if (!pb_file.is_open())
    {
        return -1;
    }

    FileDescriptorSet file_descriptor_set;
    if (!file_descriptor_set.ParseFromIstream(&pb_file)) {
        return -1;
    }

    DescriptorPool pool;
    for (int i = 0; i < file_descriptor_set.file_size(); ++i) {
        pool.BuildFile(file_descriptor_set.file(i));
    }

    const Descriptor* person_descriptor = pool.FindMessageTypeByName("tutorial.Person");
    
    DynamicMessageFactory message_factory;
    const Message* default_person = message_factory.GetPrototype(person_descriptor);
    Message* person = default_person->New();

    const Reflection* reflection = person->GetReflection();
    reflection->SetString(person, person_descriptor->FindFieldByName("name"), "abc");
    reflection->SetInt32(person, person_descriptor->FindFieldByName("id"), );
    reflection->SetString(person, person_descriptor->FindFieldByName("email"), "abc@163.com");

    util::JsonPrintOptions json_options;
    json_options.add_whitespace = true;
    json_options.always_print_primitive_fields = true;
    json_options.preserve_proto_field_names = true;
    std::string output;
    util::MessageToJsonString(*person, &output, json_options);
    std::cout << "====== Person data ======" << std::endl;
    std::cout << output;

    delete person;
}

輸出

====== Person data ======
{
 "name": "abc",
 "id": ,
 "email": "abc@163.com",
 "phones": []
}

網(wǎng)頁標(biāo)題:Protobuf 動(dòng)態(tài)加載 .pb 文件并操作 Message
網(wǎng)站網(wǎng)址:http://chinadenli.net/article46/dsogoeg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供外貿(mào)建站Google、網(wǎng)站收錄外貿(mào)網(wǎng)站建設(shè)、自適應(yīng)網(wǎng)站App開發(fā)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

商城網(wǎng)站建設(shè)