Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Python functions from C++

I am trying to achieve call Python functions from C++. I thought it could be achieved through function pointers, but it does not seem to be possible. I have been using boost.python to accomplish this.

Say there is a function defined in Python:

def callback(arg1, arg2):
    #do something
    return something

Now I need to pass this function to C++, so that it can be called from there. How do I write the code on C++ side using boost.python to achieve this?

like image 855
Amar Avatar asked Dec 02 '10 04:12

Amar


People also ask

Can I call a Python function in C?

If a C interface makes use of callbacks, the equivalent Python often needs to provide a callback mechanism to the Python programmer; the implementation will require calling the Python callback functions from a C callback. Other uses are also imaginable.

How do I connect Python to C?

There a number of ways to do this. The rawest, simplest way is to use the Python C API and write a wrapper for your C library which can be called from Python. This ties your module to CPython. The second way is to use ctypes which is an FFI for Python that allows you to load and call functions in C libraries directly.

Can I mix Python with C?

Extending Python with C or C++ It is quite easy to add new built-in modules to Python, if you know how to program in C. Such extension modules can do two things that can't be done directly in Python: they can implement new built-in object types, and they can call C library functions and system calls.


1 Answers

If it might have any name:

Pass it to a function that takes a boost::python::object.

bp::object pycb; //global variable. could also store it in a map, etc
void register_callback(bp::object cb)
{
      pycb = cb;
}

If it is in a single known namespace with a consistent name:

bp::object pycb = bp::scope("namespace").attr("callback");

bp::object has operator() defined, so you call it just like any function

ret = pycb()
like image 195
Matthew Scouten Avatar answered Oct 24 '22 12:10

Matthew Scouten