Pybind11 中的类绑定
1. 基本类绑定示例
#include <pybind11/pybind11.h>
namespace py = pybind11;
class Pet {
public:
Pet(const std::string &name) : name(name) {}
void setName(const std::string &name_) { name = name_; }
const std::string &getName() const { return name; }
private:
std::string name;
};
PYBIND11_MODULE(example, m) {
py::class_<Pet>(m, "Pet")
.def(py::init<const std::string &>())
.def("setName", &Pet::setName)
.def("getName", &Pet::getName);
}
2. 类绑定高级特性
- 构造函数重载:
.def(py::init<const std::string &>())
.def(py::init<>())
- 成员变量绑定:
.def_readwrite("name", &Pet::name)
.def_readonly("name", &Pet::name)
- 静态成员:
.def_static("static_method", &Pet::staticMethod)
- 继承:
如果不声明继承,则需要手动绑定子类方法。
py::class_<Dog, Pet>(m, "Dog")
.def(py::init<const std::string &>());
3. 类型转换注意事项
Python 类型 | C++ 类型 | 说明 |
---|
None | std::nullptr_t | 空值 |
bool | bool | 布尔值 |
int | int , long , unsigned int , size_t | 整数 |
float | float , double | 浮点数 |
str | std::string , char* , std::string_view | 字符串 |
bytes | std::string , char* , std::string_view | 字节串 |
tuple | std::tuple<...> | 元组 |
list | std::vector<...> , std::list<...> | 列表 |
dict | std::map<...> , std::unordered_map<...> | 字典 |
set | std::set<...> , std::unordered_set<...> | 集合 |
function | std::function<...> | 函数/可调用对象 |
object | py::object | 通用 Python 对象 |
Any | py::object 或模板参数 | 任意类型 |
array.array | std::array<...> | 固定大小数组 |
numpy.ndarray | py::array_t<...> | NumPy 数组 |
memoryview | py::memoryview | 内存视图 |
slice | py::slice | 切片对象 |
type | py::type | 类型对象 |
- 自动转换:Pybind11 会自动在 Python 和 C++ 类型之间进行转换。
- 自定义类型:可以使用
py::class_
绑定自定义 C++ 类型。 - 类型检查:可以使用
py::isinstance<...>()
检查 Python 对象的类型。 - 类型转换失败:如果转换失败,Pybind11 会抛出
py::cast_error
异常。 - STL 容器:Pybind11 提供了对 STL 容器的自动转换支持,包括
std::vector
, std::map
等。 - NumPy 支持:通过
py::array_t
可以高效地与 NumPy 数组交互。 - 智能指针:支持
std::shared_ptr
, std::unique_ptr
等智能指针类型。