c++ - 在 C++ 中提取从 C++ 类继承的 Python 对象

标签 c++ boost boost-python

我想从 C++(Base) 导出一个抽象类以在 Python(Derived) 中创建一个继承类,最后提取该类以创建一个 C++ 指针对象(Base*)。我找到 this solution.但它对我不起作用,尽管它可以编译,但执行会因异常而停止。
我的代码是这样的:

#if PY_MAJOR_VERSION >= 3
#   define INIT_MODULE PyInit_module
    extern "C" PyObject* INIT_MODULE();
#else
#   define INIT_MODULE initmodule
    extern "C" void INIT_MODULE();
#endif

int main()
{
    PyImport_AppendInittab((char*)"module", INIT_MODULE);
    Py_Initialize();
    object main = import("__main__");
    object global = main.attr("__dict__");
    PySys_SetPath(L".");
    global["derivedmodule"] = import("derivedmodule");
    object obj = eval("derivedmodule.Derived()", global);
    extract<Base*> ex(obj); // Here is the problem, the extraction didn't work
                            // { <boost::python::converter::extract_pointer<module::Base*>> =   
                            //   {m_source = 0x7ffff6f94030,
                            //    m_result = 0x0}, <No data fields>}
    if(ex.check()){
        Base * const b = ex(); 
        b->foo();  
        std::cout << "SUCCESS\n";
        return 0;
    } else {
        std::cout << "FAIL\n"; // Always jumps here.
        return 1;
    }

}

“模块”和“派生模块”在 python 解释器上工作。

最佳答案

我终于找到了解决方案。在“派生模块”中,该类必须像这样初始化基类:

class Derived(derivedmodule.Base):
def __init__(self):
    derivedmodule.Base.__init__(self)

并且导入的 Base 类必须具有这样的 init 函数:
class_<BaseWrap, /*Holder*/, boost::noncopyable>("Base", init<>())
// The holder could be empty or a class like shared_ptr<Base>, but the essential is the init<>() function.

关于c++ - 在 C++ 中提取从 C++ 类继承的 Python 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61769980/

相关文章:

c++ - Boost 插件选择

c++ - static_cast 会影响简单类型 float 的 Boost 吗?

python - 从 C++ 矢量到 Numpy ndarray 的转换非常慢

c++ - 在 C++ 静态 boost::shared_ptr 中保存 python 生成的值

python - 使用 boost::python 将数据缓冲区放入 C++

c++ - 使用谷歌分析跟踪 C++ 应用程序

c++ - 从 std::string 的两端删除子字符串?

c++ - 使用 Windows 窗体在 Visual Studio C++ 中进行线程绘图

c++ - 为什么不能从 max double 中减去 1

c++ - 与模板方法的接口(interface)