【问题标题】:Extract in C++ a Python object inherited from C++ Class在 C++ 中提取从 C++ 类继承的 Python 对象
【发布时间】:2020-08-29 08:55:06
【问题描述】:

我想从 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;
    }

}

“module”和“derivedmodule”在python解释器上工作。

【问题讨论】:

    标签: c++ boost boost-python


    【解决方案1】:

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

    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.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多