1. 函数重载介绍
If you have a C++14 compatible compiler [2], you can use an alternative syntax to cast the overloaded function:
py::class_<Pet>(m, "Pet")
.def("set", py::overload_cast<int>(&Pet::set), "Set the pet's age")
.def("set", py::overload_cast<const std::string &>(&Pet::set), "Set the pet's name");
py::overload_cast 只需要制定输入参数的类型,函数的返回值类型会自动推断,省去了很多麻烦
.def("foo_mutable", py::overload_cast<int, float>(&Widget::foo))
Here, py::overload_cast
only requires the parameter types to be specified. The return type and class are deduced.
This avoids the additional noise of void (Pet:😗)() as seen in the raw cast.
If a function is overloaded based on constness, the py::const_
tag should be used:
struct Widget {
int foo(int x, float y);
int foo(int x, float y) const;
};
py::class_<Widget>(m, "Widget")
.def("foo_mutable", py::overload_cast<int, float>(&Widget::foo))
.def("foo_const", py::overload_cast<int, float>(&Widget::foo, py::const_));
2. 完整代码
- struct_pet.h
#include<iostream>
struct Pet{
Pet(const std::string &name_, int age_){
name = name_;
age = age_;
}
void set(int age_){
age = age_;
}
void set(const std::string &name_){
name = name_;
}
std::string name;
int age;
};
- struct_pet_warp.cpp
#include<iostream>
#include <pybind11/pybind11.h>
#include "struct_pet.h"
namespace py = pybind11;
PYBIND11_MODULE(struct_pet, m){
py::class_<Pet>(m, "Pet", py::dynamic_attr() )
.def(py::init<const std::string &, int>() )
.def("set", py::overload_cast<int>(&Pet::set), "set pet's age")
.def("set", py::overload_cast<const std::string &>(&Pet::set), "set pet's name")
.def("__repr__", [](const Pet &a){return "<struct_pet.Pet name: "+a.name+">";})
.def_readwrite("name", &Pet::name)
.def_readwrite("age", &Pet::age);
}
- test_struct.py
from struct_pet import Pet
pet = Pet("tbc", 23)
print(pet.name, pet.age )
pet.set(10)
print(pet.name, pet.age )
pet.set("dindings")
print(pet.name, pet.age )
result:
tbc 23
tbc 10
dindings 10
ref:
https://pybind11.readthedocs.io/en/stable/classes.html#overloaded-methods