How to use Python object in C++?

PythonServer Side ProgrammingProgrammingC++

Here is an example in which a simple Python object is wrapped and embedded. We are using  .c for this, c++ has similar steps −

class PyClass(object):
    def __init__(self): = []
    def add(self, val):
    def __str__(self):
        return "Data: " + str(
cdef public object createPyClass():
    return PyClass()
cdef public void addData(object p, int val):
cdef public char* printCls(object p):
    return bytes(str(p), encoding = 'utf-8')

We compile with cython pycls.pyx (use --cplus for c++) to generate a .c and .h file containing the source and the function declarations respectively. We now create a main.c file that starts up Python and we are ready to call these functions −

#include "Python.h"   // Python.h always gets included first.
#include "pycls.h"    // Include your header file.
int main(int argc, char *argv[]){
    Py_Initialize();   // initialize Python
    PyInit_pycls();    // initialize module (initpycls(); in Py2)
    PyObject *obj = createPyClass();
    for(int i=0; i<10; i++){
        addData(obj, i);
    printf("%s\n", printCls(obj));
    return 0;

Compiling this with the proper flags (which you can obtain from python3.5-config of python-config [Py2]) −

gcc pycls.c main.c -L$(python3.5-config --cflags) -I$(python3.5-config --ldflags) -std=c99

will create our executable which interacts with our object −

Data: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

All this was done by using Cython along with the public keyword that generates the .h header file. We could alternatively just compile a python module with Cython and create the header/handle the additional boilerplate ourself.

Published on 29-Jan-2018 11:56:08