---
title: "protobuf extension"
author: "tcspecial"
date: "2019-03-23T21:56:58Z"
tags: ["protobuf"]
categories: ["开源软件"]
slug: "protobuf-extension"
draft: false
lastmod: "2019-03-23T21:56:58Z"
id: 2439286
url: "https://tcspecial.iteye.com/blog/2439286"
---

有时需要扩展公共模块的功能，各个子模块实现各自业务逻辑，protobuf 提供了extensions用于处理该场景。

 

公共协议comm\_info.proto

```
package test;

message CommReq
{
	optional int id = 1;
	extensions 10000 to 12000;	  // 预留[10000,12000]用于扩展
}
```

 

 业务模块user\_info.proto

```
import "pb/comm_info.proto";

package test;

message UserInfo
{
	optional uint32 dwIntf = 1;
}
```

 

c++调用方式：

```
// 设置扩展字段
CommReq sReq;
UserInfo *stUserInfo = sReq.MutableExtension(test::stUserInfo);
stUserInfo->set_ddwnonce(msg->nonce());
stUserInfo->set_ddwappid(msg->appid);

// 获取扩展字段
int srvid = sReq.GetExtension(test::stUserInfo).dwintf();
```

 

参考链接：

[Google protobuf](https://developers.google.com/protocol-buffers/docs/proto#extensions)