1

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?

1

2 Answers 2

3

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.

2
  • Thanks. I cannot find h2py on my machine (Fedora FC16). YUM does not give me any hint on where to get it from. I nevertheless found the source (copy/paste it) and it does what I want. If you know how I should get h2py more "cleanly" let me know. and thanks for your answer. Feb 23, 2012 at 10:40
  • @user1159290 There is a separate package, python-tools I think, for Fedora. But you don't need more than the script itself. Feb 23, 2012 at 11:18
1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.