Note that there was a peculiar example that "I want to share constants between Python and C ++, I want to fix constants on the C ++ side at compile time, and I want to use the same variables in Python".
Defined in .h from Python
sample.h
#ifndef _PARAM
#define _PARAM
#define NUM 10
#define epoch 100
#endif
Take out a constant like this. This time, global variables defined by const int
etc. are not considered because it is troublesome to classify cases.
def read_header_and_get_macro(header_filepath):
with open(header_filepath, mode='r') as f:
lst = [s.strip() for s in f.readlines()]
comment_flg = False
for l in lst:
items = l.split()
if len(items) != 0 and items[0] == "/*":
comment_flg = True
continue
if comment_flg == True:
if len(items) != 0 and items[0] == "*/":
comment_flg = False
continue
if len(items) < 2 or items[0] != "#define":
continue
if items[1] in globals():
if items[2] == 'true':
globals()[items[1]] = True
elif items[2] == 'false':
globals()[items[1]] = False
else:
try:
globals()[items[1]] = float(items[2])
except ValueError:
try:
globals()[items[1]] = int(items[2])
except ValueError:
globals()[items[1]] = items[2]
3rd line
lst = [s.strip() for s in f.readlines()]
Read the file and list it line by line. This time I took a list for each line and turned it in a list, but I am free to turn f.readline ()
for statement separately
4th line
comment_flg = False
In C (++), everything from / *
to the end with * /
is a comment, so a flag to remember this.
6th line
items = l.split()
Get a list of the contents of the line, which is divided by half-width spaces.
['#define', 'NUM', '10']
I wanted a list like this.
7th line~13th line
if len(items) != 0 and items[0] == "/*":
comment_flg = True
continue
if comment_flg == True:
if len(items) != 0 and items[0] == "*/":
comment_flg = False
continue
As mentioned above, comments are excluded.
14th line~Line 15
if len(items) < 2 or items[0] != "#define":
continue
Lines that do not start with #define
are excluded because no macro is defined.
16th line~Line 28
if items[1] in globals():
if items[2] == 'true':
globals()[items[1]] = True
elif items[2] == 'false':
globals()[items[1]] = False
else:
try:
globals()[items[1]] = float(items[2])
except ValueError:
try:
globals()[items[1]] = int(items[2])
except ValueError:
globals()[items[1]] = items[2]
Other than the previous ones should be constants. At this time, ʻitems [1] should contain a constant name, so ʻitems [1] in globals ()
is used to check if this is defined as a global variable. If it is defined, you can find its value with globals () [items [1]]
, so if you forcibly rewrite the variable, it will be completed. However, we are processing to align the C ++ bool type to Python, and we are also converting float / int / str.
Recommended Posts