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?

6
  • Add an attribute to a module with given value Commented Jan 23, 2022 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. Commented Jan 23, 2022 at 15:12
  • What's you're missing is that parsing this in Python would be trivial. Commented Jan 23, 2022 at 15:27
  • @martineau I wrote that I could easily write a parser myself... Commented Jan 23, 2022 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 Commented Jan 23, 2022 at 17:35

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

This is perfect! I knew something like it must have existed, wonder why it was not more widely known!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.