我想从 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/