Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Google Protobuf Map in C++?

I am attempting to use the new protobuf Map functionality in C++.

The following was done on Ubuntu 14.04 with gcc 4.9.2 C++14 and protobuf 3.0.0-alpha-4:

Message definition:

message TestMap {
     map<string,uint64> map1 = 1;
}

Then, I tried to compile the following example program:

auto test = debug::TestMap::default_instance();
auto map = test.mutable_map1();
string key = "key";
uint64 val = 20;
map[key] = val;

Acccessing the map using the [] syntax works totally fine for std::unordered_map. But the protobuf implementation always yields the following compiler error:

error: no match for ‘operator[]’ (operand types are ‘google::protobuf::Map<std::basic_string<char>, long unsigned int>*’ and ‘std::string {aka std::basic_string<char>}’)

I do not understand why this operator is not known, because the header file google::protobuf::Map is clearly found and this should be an elementary operation.

Do you have any idea what goes wrong here? I would welcome any example of using the new protobuf maps, as I haven't found any online after researching for hours.

like image 301
Daniel Becker Avatar asked Jun 03 '15 13:06

Daniel Becker


People also ask

Does protobuf support map?

According to Google protobuf doc, proto 2 does support map type https://developers.google.com/protocol-buffers/docs/proto#maps . As I quote, Maps cannot be repeated, optional, or required.

What is protobuf C?

This is protobuf-c, a C implementation of the Google Protocol Buffers data serialization format. It includes libprotobuf-c , a pure C library that implements protobuf encoding and decoding, and protoc-c , a code generator that converts Protocol Buffer . proto files to C descriptor code.

What is the difference between proto2 and proto3?

proto3 is the current version of the language. This is the most commonly used version of the language. We encourage new code to use proto3. proto2 is an older version of the language.


1 Answers

As Pixelchemist pointed out, the problem is that map is a pointer so the [] operator does not work.

Thus, the pointer needs to be dereferenced first. *map[key] also does not work, as the compiler first parses [] and then the *. The following does work:

(*map)[key] = val;

Although this is a quite basic problem, this represents a good learning opportunity for C++ and Protocol Buffers.

like image 188
Daniel Becker Avatar answered Sep 19 '22 13:09

Daniel Becker