Search code examples
pythonc++boostboost-pythonpython-bindings

Python binding of functions within a c++ program


I have a program written in c++ that functions on it's own, however we want to make it accessible to Python. Specifically, we have several functions that are more efficient in c++, but we do a lot of other things with the output using Python scripts. I don't want to rewrite the whole of main() in Python as we make use of Boost's root finding algorithms and other functionalities that'd be a pain to do in Python.

Is it possible to add Python binding to these functions while keeping the c++ main()? I've never done Python binding before, but I've looked at Boost.python since we're already using Boost. Most of the examples use c++ functions/classes in a hpp file and embed them into a python program, which isn't exactly what we want.

What we want is to keep our c++ program as a standalone so it can run as it is if users want, and also allow users to call these functions from a Python program. Being able to use the same Makefile and exe would be great. We don't really want to make a separate c++ library containing the bound functions; we're not interested in making a pythonic version of the code, merely allowing access to these useful functions.

Thanks


Solution

  • We have an extensive c++ library which we made available to python through use of a python wrapper class which calls an interface that we defined in boost python.

    One python class handles all the queries in a pythonic manner, by calling a python extension module written in c++ with boost python. The python extension executes c++ code, so it can link and use anything from the original library.

    You said your c++ is an executable, though. Why can't you use system calls to launch a shell process? You can do that in any language, including python. What I thought was you want to access individual functions, which means you need all your functions in a static library.

    You build your c++ exe normally, linking the common code. You make a "boost python extension module" which links the common code, and can be imported by a python script. And of course a unit test executable, which links and tests the common code. My preference is that the common code be a stand-alone static lib (use -fPic if there's a posix gcc build).