用pybind11包装C++抽象类时出错
Error by wrapping C++ abstract class with pybind11
我试图做一个简单的例子,用pybind包装一个抽象C++类。代码为:
#include <pybind11/pybind11.h>
#include <ostream>
#include <iostream>
namespace py = pybind11;
using namespace std;
class Base
{
public:
virtual void test() = 0;
};
class Derived: public Base
{
public:
void test() {cout << "Test";}
};
PYBIND11_MODULE(example,m) {
py::class_<Base, Derived>(m, "Base")
.def(py::init<>())
.def("test", &Derived::test);
}
当我运行以下命令时
c++ -O3 -Wall -shared -std=c++11 -fPIC `python3 -m pybind11 --includes` abstract_test.cpp -o example`python3-config --extension-suffix`n
我得到错误:
In file included from abstrakt_test.cpp:1:
/home/anaconda3/envs/pybind/lib/python3.8/site-packages/pybind11/include/pybind11/pybind11.h: In instantiation of ‘Return (Derived::* pybind11::method_adaptor(Return (Class::*)(Args ...)))(Args ...) [with Derived = Base; Return = void; Class = Derived; Args = {}]’:
/home/anaconda3/envs/pybind/lib/python3.8/site-packages/pybind11/include/pybind11/pybind11.h:1118:45: required from ‘pybind11::class_<type_, options>& pybind11::class_<type_, options>::def(const char*, Func&&, const Extra& ...) [with Func = void (Derived::*)(); Extra = {}; type_ = Base; options = {Derived}]’
abstrakt_test.cpp:23:36: required from here
/home/anaconda3/envs/pybind/lib/python3.8/site-packages/pybind11/include/pybind11/pybind11.h:1032:19: error: static assertion failed: Cannot bind an inaccessible base class method; use a lambda definition instead
static_assert(detail::is_accessible_base_of<Class, Derived>::value,
^~~~~~
/home/anaconda3/envs/pybind/lib/python3.8/site-packages/pybind11/include/pybind11/pybind11.h:1034:12: error: cannot convert ‘void (Derived::*)()’ to ‘void (Base::*)()’ in return
return pmf;
^~~
您需要"包裹";CCD_ 1。否则,您将在导入时得到以下异常:
ImportError: generic_type: type "Derived" referenced unknown base type "Base"
此外,Derived
的包装顺序错误:
py::class_<Derived, Base>(m, "Derived")
完整示例:
PYBIND11_MODULE(example,m) {
py::class_<Base>(m, "Base");
py::class_<Derived, Base>(m, "Derived")
.def(py::init<>())
.def("test", &Derived::test);
}
相关文章:
- 重载操作程序时出错>>用于类中的字符串 memebr
- 无法创建抽象类的实例
- 用pybind11包装C++抽象类时出错
- 如何处理从一个对象传递到另一个在C++中具有公共抽象类的对象的消息
- 有没有办法按值将纯抽象类的所有子类传递给 C++ 中的函数?
- 抽象类错误,请参阅声明" "是抽象的
- 将自定义函数传递到基抽象类中以延迟执行
- 将包含抽象类和普通类C++包导出到 Python
- C++:处理抽象类中的错误时出现问题
- C ++如何在原始抽象类中创建一个函数,该函数接受派生类的输入
- 在 C++ 中使用另一个头文件中的抽象类
- ATL::CComContainedObject<contained>: C2259 无法实例化抽象类
- C++:从抽象类重写纯虚拟运算符重载
- 如何创建shared_ptr抽象类的容器
- .h 或.cpp文件中的抽象类或两者兼而有之?
- 从抽象类继承以创建另一个抽象类时,我应该重新声明所有虚函数吗?
- 尝试定义派生自抽象类的类类型的对象时出错
- 扩展模板抽象类时出错
- 抽象类在创建派生类的对象时出错
- 转换基指针时出错:“不能实例化抽象类”