【问题标题】:Boost Python , python functions and ptrsBoost Python , python 函数和 ptrs
【发布时间】:2013-11-11 22:18:19
【问题描述】:

我的共享库中有一个函数指针,用于调用主引擎。 (效果很好):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

如何使它工作?泰!

【问题讨论】:

    标签: c++ python pointers boost boost-python


    【解决方案1】:

    如果调用函数指针func_ptr时在function()发生崩溃,那么执行已经通过了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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多