Conversion between C structs (C++ POD) and google protobufs?

☆樱花仙子☆ 提交于 2019-12-03 14:07:01

I could not find a ready solution for this problem, if there is one, please let me know!

If you decide to roll your own in python, the python bindings for gdb might be useful. You could then read the symbol table, find all structs defined in specified file, and iterate all struct members. Then use <gdbtype>.strip_typedefs() to get the primitive type of each member and translate it to appropriate protobuf type.

This is probably safer then a text parsers as it will handle types that depends on architecture, compiler flags, preprocessor macros, etc.

I guess the code to convert to and from protobuf also could be generated from the struct member to message field relation, but does not sound easy.

Dino

Protocol buffers can be built by parsing an ASCII representation using TextFormat. So one option would be to add a method dumpAsciiProtoBuf to each of your structs. The method would dump any simple fields (like strings, bools, etc) and call dumpAsciiProtoBuf recursively on nested structs fields. You would then have to make sure that the concatenated result is a valid ASCII protocol buffer which can be parsed using TextFormat.

Note though that this might have some performance implications (since parsing the ASCII representation could be expensive). However, this would save you the trouble of writing a converter in a different language, so it seems to be a convenient solution.

I would not parse the C source code myself, instead I would use the LibClang to parse C files into an AST and my own AST walker to generate the Protobuf and the transcoders as necessary. Googling for "libclang walk AST" should give something to start with, like ast-walker.cc and ast-dumper.cc from this github repository, for example.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!