Search code examples
pythonc++cythonboost-python

importing functions from .cpp file into python


Let me start with a disclaimer that i'm putting this question after lot of research and not finding any direct and step by step example.

Have gone through Cython , SWIG, Boostpython documentation but couldn't get a step by step process and so posting here -

I have a .cpp & .h file with couple of mathematical functions defined.I want to call them in a python (.py) code file.

How do i integrate?Which is the best and neatest way to go about it. Please illustrate


Solution

  • Since i eventually solved it using some of the help provided here and research , let me post the answer.

    I did the import of CPP function via Python using Cython.

    Cython wraps the Python code with CPP file and compiles the two. The outcome is a Python module (name of the module can be specified in setup.py file ) and the module can be called as usual.

    The issue i was facing was calling a CPP function from Python.So here are my tips for working it out

    1. Define your function in C++ Header and CPP file.
    2. Using cdef , define the function in Python script in the beginning where you import modules define other variables.This definition is similar to C++ header file definition
    3. While pasing arguments and arrays to the function call from python , ensure all variables and arrays are type casted as CPP.
    4. For arrays, it is a bit tricky. E.G. a double array in Python can be type casted using array.array(array_to_cast). In the following example, we cast the python array, dev, into the c++ array, dev_arr. Note that dev is an array of type double in python, hence the first parameter input to array.array() is 'd'.
    cdef array.array dev_arr = array.array('d',dev)   
    

    While passing the dev_arr array to your main CPP function, you have to specify this array :data.as_doubles

    fn_response = cpp_fn_call(stddev_arr.data.as_doubles,...)
    

    Rest will work smoothly.