'Use C preprocessor macros (just the constants) as Python variables
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?
Solution 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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
