在C ++中提取从C ++类继承的Python对象 [英] Extract in C++ a Python object inherited from C++ Class

查看:83
本文介绍了在C ++中提取从C ++类继承的Python对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从C ++(Base)导出一个抽象类,以便在Python(Derived)中创建一个继承的类,并最终提取该类以创建C ++指针对象(Base *).我找到了此解决方案.,尽管它可以编译,但它对我不起作用,执行异常终止.我的代码是这样的:

I want to export an abstract class from C++(Base) to create an inherited class in Python(Derived) and finally extract that class for create a C++ pointer object(Base*). I find this solution. but it didn't work for me although it compiles, the execution halt with an exception. My code is this:

#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解释器上工作.

"module" and "derivedmodule" work on python interpreter.

推荐答案

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

I finally found a solution. In the "derivedmodule" the class must initialize the base class like this:

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

导入的Base类必须具有如下的init函数:

And the imported Base class must have the init function like this:

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 ++类继承的Python对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆