Pybind11 无法绑定成员函数中的右值引用参数 我使用pybDun11为C++库创建Python绑定,它的源代码不能更改。它包含一个类,该类使用右值引用参数定义成员函数(例如T&&val)。我无法创建到具有右值引用参数的成员函数的绑定,但到具有相同参数的非成员函数的绑定工作正常
简化的示例如下所示:Pybind11 无法绑定成员函数中的右值引用参数 我使用pybDun11为C++库创建Python绑定,它的源代码不能更改。它包含一个类,该类使用右值引用参数定义成员函数(例如T&&val)。我无法创建到具有右值引用参数的成员函数的绑定,但到具有相同参数的非成员函数的绑定工作正常,pybind11,Pybind11,简化的示例如下所示: struct Foo { // Cannot create a pybinding for this method. void print_ref(int &&v) const { std::cout << "Foo::print_ref(" << to_string(v) << ")" <<std::endl; } }; // Pybinding for st
struct Foo {
// Cannot create a pybinding for this method.
void print_ref(int &&v) const {
std::cout << "Foo::print_ref(" << to_string(v) << ")" <<std::endl;
}
};
// Pybinding for standalone function works as expected.
void print_ref(int&& val) {
std::cout << "print_ref(" << to_string(val) << ")" << std::endl;
};
PYBIND11_MODULE(refref, m) {
py::class_<Foo>(m, "Foo")
// Both of these attempts to create a pybinding FAILs with same error.
.def("print_ref", &Foo::print_ref)
.def("print_ref", (void (Foo::*) (int&&)) &Foo::print_ref);
// This pybinding of standalone function is SUCCESSful.
m.def("print_ref", &print_ref);
}
structfoo{
//无法为此方法创建pybinding。
无效打印参考(int&v)常量{
std::cout事实上,问题来自于rvalues
。我从和中学到了很多东西。
有一个很好的解决方法:您可以创建一个包装类,它将重定向调用到不能更改的C++库,并使用<代码> STD::移动< /COD>语义> /P>来处理<代码> rValue/Cuff>。
#include <iostream>
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
namespace py = pybind11;
struct Foo {
void print_ref(int&& v) const {
std::cout << "Foo::print_ref(" << +v << ")" <<std::endl;
}
};
// This class will interface between PyBind and your library
class Foo_wrap{
private:
Foo _mimu;
public:
void print_ref(int v) const{
_mimu.print_ref(std::move(v));
}
};
PYBIND11_MODULE(example, m) {
py::class_<Foo_wrap>(m, "Foo_wrap")
.def(py::init())
.def("print_ref", &Foo_wrap::print_ref);
}
#include <iostream>
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
namespace py = pybind11;
struct Foo {
void print_ref(int&& v) const {
std::cout << "Foo::print_ref(" << +v << ")" <<std::endl;
}
};
// This class will interface between PyBind and your library
class Foo_wrap{
private:
Foo _mimu;
public:
void print_ref(int v) const{
_mimu.print_ref(std::move(v));
}
};
PYBIND11_MODULE(example, m) {
py::class_<Foo_wrap>(m, "Foo_wrap")
.def(py::init())
.def("print_ref", &Foo_wrap::print_ref);
}
import example as fo
wr = fo.Foo_wrap()
wr.print_ref(2)