1

我的共享库中有一个函数指针,用于调用主引擎。(效果很好):func_ptr

我还有一个 python 模块,我在我的程序中使用 boost::python::import("module")

我的python模块中的一个函数:

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

和我的 C++ 程序中的一个函数:

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

当我用

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

它在我的 c++ 函数中崩溃。(段错误)

gdb 产生类似的东西:

http://pastebin.com/NRdupqp6

如何使它起作用?泰!

4

1 回答 1

0

function()如果在调用函数指针时发生崩溃func_ptr,那么执行已经通过了 Boost.Python 层。考虑:

  • 验证它func_ptr指向一个有效的函数。
  • 测试func_ptr指向的函数是否正确处理参数值"TEST "

module.py

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

并且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();
  }
}

该应用程序产生以下输出:

engine: TEST 
result: 42
于 2013-11-15T14:10:49.153 回答