Get macro constants from C (++) header file (.h) in Python

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]

What you are doing

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

Get macro constants from C (++) header file (.h) in Python
Get data from Quandl in Python
Get exchange rates from open exchange rates in Python
Write O_SYNC file in C and Python
Get battery level from SwitchBot in Python
Generate C language from S-expressions in Python
Get Precipitation Probability from XML in Python
Get metric history from MLflow in Python
Get compliments from new girls in C # paizahack_01
From file to graph drawing in Python. Elementary elementary
Call a Python script from Embedded Python in C ++ / C ++
Get only articles from web pages in Python
File operations in Python
File processing in Python
Next Python in C
File operations in Python
Get date in Python
C API in Python 3
Get data from GPS module at 10Hz in Python
Store node structure in C ++ from NetworkX file format
Python hand play (get column names from CSV file)
Get YouTube Comments in Python
Assigned scaffolding macro in Python script file to F12 key
Get your heart rate from the fitbit API in Python!
Download the file in Python
OCR from PDF in Python
Get the MIME type in Python and determine the file format
Binary search in Python / C ++
Get the value while specifying the default value from dict in Python
Get Terminal size in Python
Explicitly get EOF in python
Hit REST in Python to get data from New Relic
Get Evernote notes in Python
Get message from first offset with kafka consumer in python
Get Japanese synonyms in Python
Get 1000 posts in Python order from all Slack channels and put them together in a txt file
How to get a string from a command line argument in python
Read a file in Python with a relative path from the program
Get the formula in an excel file as a string in Python
Get Leap Motion data in Python.
Execute Python script from batch file
Call C from Python with DragonFFI
File / folder path manipulation in Python
Linebot creation & file sharing in Python
Get the desktop path in Python
ABC166 in Python A ~ C problem
Call popcount from Ruby / Python / C #
Get the script path in Python
Create a binary file in Python
Extract text from images in Python
Solve ABC036 A ~ C in Python
Get, post communication memo in Python
Tips for calling Python from C
Execute Python code from C # GUI
How to wrap C in Python
Get upcoming weather from python weather api
Run Python scripts synchronously from C #
Get the desktop path in Python
ORC, Parquet file operations in Python
Get the host name in Python
Solve ABC037 A ~ C in Python