[英]porting CPP defines to python
I have a program (written in C/C++) that behaves as a socket server. 我有一个程序(用C / C ++编写),表现为套接字服务器。 I'd like to write the client in python. 我想在python中编写客户端。 The packets exchanged over the TCP socket follow a "home-made" protocol (simple) using macros defined as #define... in a XXX.h file. 通过TCP套接字交换的数据包遵循“自制”协议(简单),使用在XXX.h文件中定义为#define ...的宏。 I'd like to parse the XXX.h file to generate a equivalent XXX.py The XXX.h file only contains CPP macro definitions (and comments) eg: 我想解析XXX.h文件以生成等效的XXX.py XXX.h文件只包含CPP宏定义(和注释),例如:
//the following commands are used when talking to the server
//A tcp message is: the command(32bit word) followed by the flags (32 bits)
#define CMD_DO_SOMETHING1 1 //this does something
#define CMD_DO_SOMETHING2 2 //that does something else
#define FLAG1 0x0001 //These flags are used as parameter in cmd2
#define FLAG2 0x0002
#define FLAG3 0x0004
#define FLAG4 0x0008
#define TEST_FLAG1(x) (x&FLAG1) //this tests for flag1
I would like to get something like: XXX.py: 我想得到类似的东西:XXX.py:
CMD_DO_SOMETHING1=1
CMD_DO_SOMETHING2=2
FLAG1=1
...
def test_flag1(x):
return(x&flag1)
I have been briefly looking at swig, but was not convinced it really did what I am looking for. 我一直在简短地看着swig,但不相信它确实做了我正在寻找的东西。 Parsing the XXX.h file manually and matching regular expression feels wrong. 手动解析XXX.h文件并匹配正则表达式感觉不对。 So does the idea of running CPP on my *.py file. 在我的* .py文件上运行CPP的想法也是如此。 At least, the constant definition should be converted so I don't have to rewrite them twice. 至少,应该转换常量定义,所以我不必重写它们两次。 Any better ideas? 有更好的想法吗?
h2py.py
does exactly that. h2py.py
这么做的。 It is included in the Python distribution(*) in Tools/scripts 它包含在工具/脚本的Python发行版(*)中
If you need to convert more than #defines, see the question Convert C++ Header Files To Python 如果您需要转换多于#defines,请参阅将C ++头文件转换为Python的问题
EDIT: (*) It is included at least in the full source distribution. 编辑:(*)它至少包含在完整的源代码发行版中。
Why wouldn't you use the macro pre-processor to do this? 为什么不使用宏预处理器来执行此操作? This is what they are for. 这就是它们的用途。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.