Ododo Ododo - 4 months ago 9x
Python Question

Boost Python , python functions and ptrs

I have a function pointer in my shared library that i am using to call a main engine.
(It works well) : func_ptr

I also have a python module that i import in my program, using boost::python::import("module")

A function in my python module:

def wrapper(function):
function('TEST ')

and a function in my c++ program:

int function(char const *msg){
func_ptr(msg); //this line crashes
return 1;

When i'm calling my wrapper function with


it crashes in my c++ function. (segfault)

gdb produces something like that :


How to make it works ? Ty !


If the crash occurs in function() when invoking the function pointer func_ptr, then execution has already passed through the Boost.Python layers. Consider:

  • Verifying that func_ptr points to a valid function.
  • Testing that the function to which func_ptr points properly handles the argument value "TEST ".

With module.py:

def wrapper(function):
   return function('TEST ')

And main.cpp:

#include <iostream>
#include <boost/python.hpp>

void engine(const char* msg)
  std::cout << "engine: " << msg << std::endl;

void (*func_ptr)(const char* msg) = &engine;

int function(const char* msg)
  return 42;

int main()

  namespace python = boost::python;
    // Import the 'module' module.
    python::object module = python::import("module");

    // Invoke the wrapper function in the module, providing function
    // as a callback.
    python::object result = 

    std::cout << "result: " << python::extract<int>(result) << std::endl;
  catch (python::error_already_set&)

The application produces the following output:

engine: TEST 
result: 42