How to import efficiently values in Python from a list of global variables in a C header file

127 views Asked by At

I would like to find an efficient and quick way to load the values of a list of global variables from a C header file into Python. For instance, suppose I have the file header.h:

/* comments */
int param_nx=2049; // comment
int param_ny=2049; // comment
double param_dt=0.01; // comment

Is there an easy way to read this file with Python, skip the comments, and define the corresponding variables there? I do not mind using the same variable name.

1

There are 1 answers

4
AudioBubble On BEST ANSWER

Try this.

import re

r = re.compile("(double|int) ([a-zA-Z_]+)=([0-9\.]+)")

header = """/* comments */
int param_nx=2049; // comment
int param_ny=2049; // comment
double param_dt=0.01; // comment"""

params = {}

for line in header.split("\n"):
    m = r.search(line.strip())
    if m:
        if m.group(1) == "int":
            params[m.group(2)] = int(m.group(3))
        elif m.group(1) == "double":
            params[m.group(2)] = float(m.group(3))
print(params)

Output:

{'param_dt': 0.01, 'param_nx': 2049, 'param_ny': 2049}