2

I have a bunch of C macros the operation of which I need to simulate in python. I saw some pointers to pygccxml or ctypeslib etc. Are these the ways to go? Or is there something out there that is better ?

The C macros if and when they change, I would like the python implementation to be auto generated rather than having to make manual modifications. Hence the question.

my_c_header.h:

#ifdef OS

#define NUM_FLAGS   (uint16_t)(3)
#define NUM_BITS    (uint16_t)(8)

#else

#define NUM_FLAGS   (uint16_t)(6)
#define NUM_BITS    (uint16_t)(16)
#endif

#define MAKE_SUB_FLAGS    (uint16_t)((1<<NUMFLAGS) -1)

#define MAKE_TOTAL_FLAGS(x)  (uint16_t)((x & MAKE_SUB_FLAGS) >> NUM_BITS)

/* #defines type 2 */

#ifdef OS
#DO_SOMETHING(X)  os_specifc_process(x)
#else
#DO_SOMETHING(x)  
#endif

/* #defines type 3 */

enum
{
CASE0,
CASE1,
CASE2
}

#define MY_CASE_0     ((uint16_t)CASE0)
#define MY_CASE_1     ((uint16_t)CASE1)
#define MY_CASE_2     ((uint16_t)CASE2)


/*End of file <my_c_header.h> */
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user253854
  • 21
  • 1
  • 3
  • How complex are these macros? Macros in C can of course be anything (as they're just textual substitution), but generally "sane" ones can be quite simple, perhaps merely mathematical expressions with limited or no calls to functions. What do yours look like? (Examples?) – Peter Hansen Apr 16 '10 at 18:59
  • It would also help to understand more about what you're doing: is this for automated testing or something like that? I made a `parse_c.py` for testing some 68HC12 code (embedded CPU) that can handle stuff about the complexity of what you show. Within certain limits, it handles enums, structs (building ctypes Structures), and evaluates (using Python eval) macros as you show above. It's crude, but depending on your needs it may be about what you want (with some work). Eli Bendersky's http://code.google.com/p/pycparser/ may be a good place to start: I'd begin there if I were to start over. – Peter Hansen Apr 17 '10 at 15:49
  • It would have been a case of simply using pre-existing C libraries from Python code using 'ctypes' or similar, except for the complication brought in by the need to calculate parameters passed into the C library API using the header of the form posted in the orignal message. Any suggestions ? – user253854 Apr 19 '10 at 08:27
  • This question has been answered in another thread later http://stackoverflow.com/questions/12147394/how-can-i-reference-defines-in-a-c-file-from-python – Matti Lyra Aug 28 '12 at 07:30
  • code.google.com/p/pycparser is in the 404 wind – vwvan Dec 09 '18 at 05:17

1 Answers1

1

If you are writing an extension module, use https://docs.python.org/3/c-api/module.html#c.PyModule_AddIntMacro

wkschwartz
  • 3,817
  • 2
  • 29
  • 33