Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a C function in Python [closed]

Tags:

python

c

parsing

Say I want to parse a C function in a Python script and want to get a list with all the types of the arguments and only the arguments for the C function. How would I go about doing this efficiently?

E.g.: With this function

uint32_t foo(char a, int b, double* c, uint64_t d);

I want output ['char', 'int', 'double*', 'uint64_t']

like image 607
Leon He Avatar asked Mar 03 '26 21:03

Leon He


1 Answers

I think what you want is to parse the "prototype of a C function". When you say parse a "C function" ordinarily one would assume that you are doing what a compiler might do with the source implementation.

In your example, you only show a prototype. In the real world, you will encounter many complications that might make you choose another approach. Your killer is the C preprocessor. In an insane piece of code the real type of 'a' could actually be double* due to a really bad macro. You also might have pointers to structs, typedefs for function pointers, etc.

There is a complication that absolutely defies a solution to your problem. The compilation of the prototype will depend on command line arguments to a C compiler describing where to find header files. Without that metadata, you are hosed. With it, you would really want to run the C preprocessor first - check your compiler documentation for how to do so. Then your python program could read the output.

That line might not even be in it - LOL - if it happened to be surrounded by a #if construct that eliminated it.

These features of the C language are the features that make it really nasty to do things like write programs that operate on C, such as a refactoring engine.

like image 149
Fred Mitchell Avatar answered Mar 05 '26 11:03

Fred Mitchell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!