C结构(C ++ POD)和google protobufs之间的转换? [英] Conversion between C structs (C++ POD) and google protobufs?

查看:521
本文介绍了C结构(C ++ POD)和google protobufs之间的转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有代码,目前传递了很多(有时是嵌套的)C(或C ++ Plain Old Data)结构和数组。



我想将这些转换为/从Google protobufs转换。我可以手动编写在这两种格式之间进行转换的代码,但是自动生成这样的代码会更容易出错。这样做最好的方法是什么? (这在一个语言中很容易,用足够的反省来迭代成员变量的名称,但这是我们正在讨论的C ++代码)



考虑的是编写分析C结构体的python代码,然后吐出一个.proto文件,以及从所有类型的成员(向任意一个方向)复制的C代码,但也可能有更好的方法。或者可能还有另一个已经可以生成的IDL:


  1. .h包含所有嵌套类型的.h文件

  2. 包含等价物的
  3. .proto文件

  4. .c文件,其中包含.proto文件生成的C ++结构与.h文件中定义的结构之间复制方向的函数


解决方案

我找不到一个可以解决这个问题的解决方案,如果有的话,请让我知道!



如果您决定在python中自行滚动,,inedocs / gdb / Python-API.htmlrel =nofollow noreferrer> python绑定可能会有用。然后,您可以读取符号表,查找指定文件中定义的所有结构体,并迭代所有结构体成员。
然后使用< gdbtype> .strip_typedefs()获取每个成员的原始类型并将其转换为适当的protobuf类型。



这可能比文本解析器更安全,因为它将处理依赖于架构,编译器标志,预处理器宏等的类型。



I猜测从protobuf转换的代码也可以从结构成员到消息字段关系生成,但听起来不容易。


I have code that currently passes around a lot of (sometimes nested) C (or C++ Plain Old Data) structs and arrays.

I would like to convert these to/from google protobufs. I could manually write code that converts between these two formats, but it would be less error prone to auto-generate such code. What is the best way to do this? (This would be easy in a language with enough introspection to iterate over the names of member variables, but this is C++ code we're talking about)

One thing I'm considering is writing python code that parses the C structs and then spits out a .proto file, along with C code that copies from member to member (in either direction) for all of the types, but maybe there is a better way... or maybe there is another IDL that already can generate:

  1. .h file containing all of nested types
  2. .proto file containing equivalents
  3. .c file with functions that copy either direction between the C++ structs that the .proto file generates and the structs defined in the .h file

解决方案

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.

这篇关于C结构(C ++ POD)和google protobufs之间的转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆