0

I am writing a Python code which needs to interoperate with C code which I also wrote. In C I have a section like

#define FOO 23    // whatever
#define BAR 54.3  // something else

I want to use these in python (as regular variables is fine). I am not finding anything in my web searches, and I could easily write a parser myself, but.... I can't believe I am the first one with such a need. PyPreprocessor comes close, but not exactly.

Is there a obvious way to do so which I am missing?

Davide
  • 17,098
  • 11
  • 52
  • 68
  • Add an attribute to a module with given value – Azat Ibrakov Jan 23 '22 at 15:07
  • If you are mixing C and Python, this is done in the C code of a *builtin* module. And when you only want to use some constants in Python, the common way is to declare them *by hand* inside a module. I have never found (nor even search to be honest) a *magic tool* that would extract constants from a C header or source file to build a Python source file. – Serge Ballesta Jan 23 '22 at 15:12
  • What's you're missing is that parsing this in Python would be trivial. – martineau Jan 23 '22 at 15:27
  • @martineau I wrote that I could **easily** write a parser myself... – Davide Jan 23 '22 at 17:31
  • @SergeBallesta I am not really "mixing" the different programming languages: the C code produces some data which is then sent (via USB, but it does not really matter) to another device where the python code needs to interpret the data. Hence Python needs those constants. Because of DRY I really do not want to declare them by hand. Look like I'll do a parser – Davide Jan 23 '22 at 17:35
  • OK…in that case then the point you're missing must be that it's so easy, no one has ever bothered to put in it a package and publish it. – martineau Jan 23 '22 at 21:53

1 Answers1

1

Maybe it's overkill, but you could use parser from dissect.cstruct module.

It currently supports plain preprocessor defines and simple expressions like #define TWO (ONE+1) , but don't support conditionals like #if and #ifdef.

Code example

from dissect.cstruct import cstruct    

defs_str = """
#define FOO 23    // whatever
#define BAR 54.3  // something else
"""

c = cstruct()
c.load(defs_str)
print(c.consts)  # => {'FOO': 23, 'BAR': 54.3}
print(c.FOO)     # => 23
print(c.BAR)     # => 54.3
  • This is perfect! I knew something like it must have existed, wonder why it was not more widely known! – Davide Apr 16 '22 at 22:21