从从该抽象类派生的 Python 对象强制转换C++抽象类C++
Cast a C++ abstract class from a Python object derived from that C++ abstract class
我一直在尝试在C++程序中转换一个抽象类,尝试与此网页和官方文档不同的解决方案,例如这个和这个,但没有任何效果。 我的C++抽象类是:
class Base
{
public:
virtual ~Base(){};
virtual void foo(){};
};
我要导入 python 的包装器是:
class BasePy: public Base
{
public:
void foo() override
{
PYBIND11_OVERLOAD_PURE(
void,
Base,
foo);
}
};
我的导入功能和导入:
void import_base(pybind11::module m)
{
using namespace pybind11;
class_<Base, BasePy>(m, "Base")
.def("foo", &Base::foo);
}
PYBIND11_MODULE(baselib, m)
{
import_component(m);
}
我写了一个python类(derived.py(:
import baselib
class test(baselib.Base):
def __init__(self):
self.x = 10;
def foo(self):
print(self.x)
最后是我的主要:
scoped_interpreter guard{};
auto obj = module::import("derived").attr("test")();
// obj = {<pybind11::handle> =
// {<pybind11::detail::object_api<pybind11::handle>> =
// {<pybind11::detail::pyobject_tag> =
// {<No data fields>}, <No data fields>
// },
// m_ptr = 0x7ffff706f1d0
// },
// <No data fields>}
Base* bas = isinstance<Base>(obj) ? (Base*)obj.cast<void*>() : nullptr;
// bas = (Base*) 0x0
"baselib.so"和可执行文件编译为"derived.py"在 python3 解释器上完美运行。 在解释器中:
derived.test.__base__ : <class 'baselib.base'>
derived.test.__class__ : <class 'pybind11_builtins.pybind11_type'>
derived.baselib == baselib : true
baselib.base.__base__ : <class 'pybind11_builtins.pybind11_object'>
baselib.base.__class__ : <class 'pybind11_builtins.pybind11_type'>
我有什么不明白的?
尤里卡! 我找到了一个解决方案,当我导入类时,我没有添加蹦床类的 init 函数:
void import_base(pybind11::module m)
{
using namespace pybind11;
class_<Base,/*Holder*/ BasePy>(m, "Base")
// You can add a holder like std::shared_ptr<Base> in "Holder"
.def(init<>())// <--- THIS
.def("foo", &Base::foo);
}
在 python 类中,我们需要添加"抽象类初始值设定项"(它是蹦床初始值设定项(,如下所示:
class test(baselib.Base):
def __init__(self):
baselib.Base.__init__(self) // Adding this line
self.x = 10;
和。。。瞧!问题解决了。
相关文章:
- 无法创建抽象类的实例
- 用pybind11包装C++抽象类时出错
- 如何处理从一个对象传递到另一个在C++中具有公共抽象类的对象的消息
- 有没有办法按值将纯抽象类的所有子类传递给 C++ 中的函数?
- 抽象类错误,请参阅声明" "是抽象的
- 将自定义函数传递到基抽象类中以延迟执行
- 将包含抽象类和普通类C++包导出到 Python
- C++:处理抽象类中的错误时出现问题
- C ++如何在原始抽象类中创建一个函数,该函数接受派生类的输入
- 在 C++ 中使用另一个头文件中的抽象类
- ATL::CComContainedObject<contained>: C2259 无法实例化抽象类
- C++:从抽象类重写纯虚拟运算符重载
- 如何创建shared_ptr抽象类的容器
- .h 或.cpp文件中的抽象类或两者兼而有之?
- 从抽象类继承以创建另一个抽象类时,我应该重新声明所有虚函数吗?
- E0322:不允许使用抽象类类型 " " 的对象
- 可视抽象类 c++(错误 LNK 2001:未解析的外部符号)
- 提升 - 类没有名为"序列化"的成员(抽象类)?
- 如何将子类作为函数的参数传递给期望基类,然后将该对象传递到指向这些抽象类对象的指针向量中?
- 对纯抽象类中方法的未定义引用