Search code examples
c++pythonpointersboostboost-python

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

module.attr("wrapper")(boost::python::make_function(function))

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

gdb produces something like that :

http://pastebin.com/NRdupqp6

How to make it works ? Ty !


Solution

  • 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)
    {
      func_ptr(msg);
      return 42;
    }
    
    int main()
    {
      Py_Initialize();
    
      namespace python = boost::python;
      try
      {
        // 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 = 
            module.attr("wrapper")(python::make_function(&function));
    
        std::cout << "result: " << python::extract<int>(result) << std::endl;
      }
      catch (python::error_already_set&)
      {
        PyErr_Print();
      }
    }
    

    The application produces the following output:

    engine: TEST 
    result: 42