user1159290
user1159290

Reputation: 1003

porting CPP defines to python

I have a program (written in C/C++) that behaves as a socket server. I'd like to write the client in python. The packets exchanged over the TCP socket follow a "home-made" protocol (simple) using macros defined as #define... in a XXX.h file. 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) e.g:

//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:

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. Parsing the XXX.h file manually and matching regular expression feels wrong. So does the idea of running CPP on my *.py file. At least, the constant definition should be converted so I don't have to rewrite them twice. Any better ideas?

Upvotes: 1

Views: 1114

Answers (2)

Janne Karila
Janne Karila

Reputation: 25197

h2py.py does exactly that. It is included in the Python distribution(*) in Tools/scripts

If you need to convert more than #defines, see the question Convert C++ Header Files To Python

EDIT: (*) It is included at least in the full source distribution.

Upvotes: 3

Marcin
Marcin

Reputation: 49846

Why wouldn't you use the macro pre-processor to do this? This is what they are for.

Upvotes: 1

Related Questions