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

问题描述 投票:1回答:1

我想从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个回答
0
投票

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

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

并且导入的基类必须具有这样的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.
© www.soinside.com 2019 - 2024. All rights reserved.