Calling C ++ functions through Python Script

I have a script in which I have some functions in C ++ classes and I want to be able to use them with a python script. Let them say that I have a function

void greet(_msg); std::cout >> _msg >> std::endl; 

I want to be able to call it through a custom Python call and pass arguments to it, for example using

 saySomething("Hello") 

As a .py file, I want it to call the greet function and pass "Hello" as an argument.

I know this is a topic that has been discussed in detail, and I did some research on implementing python in C ++, I managed to read the values ​​from a python script using the standard Python / C API and run the function in Python from C ++ and pass her argument, but I can’t understand how to achieve this specific result.

I looked at ctypes and various wrapper libraries such as boost: python or swig, but I cannot understand to what extent they can help me achieve what I want.

+7
source share
3 answers

Depending on which version of Python you are interested in, 2.x or 3.x, read the Extension and Attachment section of the Python Interpreter chapter for 2.x or 3.x. You are only interested in the Python extension , so section 1. The Python extension using C or C ++ will provide you with a full explanation of how to implement what you need to be able to call your functions implemented in C ++ from a Python script.

Of course, there are many libraries and generators that allow you to wrap C / C ++ interfaces for Python (like Boost.Python or SWIG , for example), but your case sounds simple enough to learn this IMO to get to know the Python C API. Even if you use these tools, you'll often have to start with the Python C API, or at least understand it.

+5
source

I had to do this recently. Boost.Python does what we are looking for (and much more), but personally (as much as I like Boost). It seems to me that you go overboard a bit to drag half the Boost library to get one function. SWIG was also not really an option for me, since code generation always becomes a pain to maintain, while class structures change (don't get me wrong, these are BRILLIANT !, solutions just not what I was looking for).

So, the only thing left for me is to implement it from the first principles (Python / C API). Hense, "ECS: Python" was born. ECS: Python (Embedded C ++ Scripting with Python) is a simple Python C ++ cover library designed specifically for C ++ developers. It allows you to expose objects from a C ++ application to the built-in Python interpreter for interactive scripts, and it is very lightweight and easy to use.

Its free (BSD) and open source. If you are interested, this is: http://sourceforge.net/projects/ecspython

+4
source

You can use the weave.inline () function, which is part of the scipy package, to compile and execute C / C ++ files and get their results from your python script.

+3
source

All Articles