Using a common header file for Python & C

Question:

I have some consts or defines that I’m using in both a C program and a Python program however I have defined them separately in both files. It would be nice to have a single .h file that I could use for both the C and Python program to avoid having to make changes in two places.

u16 get_opt(int arg) {
    u16 mode;
    if(arg == 1) {
        mode = 0xabc1;
    } else if (arg == 2) {
        mode = 0xf104;
    } else if(arg == 3) {
        mode = 0xff16;
    }
    return mode;
}

In python I also have

MAPPING = {
    1: 0xabc1,
    2: 0xf104,
    3: 0xff16
}

def get_opt(arg) {
    return MAPPING[arg]
}

I have a lot of constant values to define which I will need access to from both a C program and a Python program so I was wondering if there’s a good way of implementing this.

Asked By: Matt

||

Answers:

Probably the easiest if doing lots of cross language programming would be SWIG (see tutorial here: http://www.swig.org/tutorial.html).

Essentially you specify your interface in an intermediate format and then run the swig tool to generate the language specific file you need.

Answered By: diverscuba23

One possible solution is to use asn1tools, it’s a Python package that can generate C files (headers and implementation files). It’s a more sophisticated tool than SWIG, but it’s a good choice if the constants shared between Python and C describe data that needs to be serialized and deserialized e.g. for sending over network.

Answered By: proski
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.