我正在努力使最简单的示例工作。这是我的代码:
// example.cpp
#include <pybind11/pybind11.h>
namespace py = pybind11;
class B {
public:
int b;
};
class A {
public:
int a;
A(int a) :a(a) {}
A(B b) { a = b.b; }
};
void fn(A) {}
PYBIND11_MODULE(example, m) {
py::class_<A>(m, "A")
.def(
py::init<int>(),
py::arg("a") = 1
);
py::class_<B>(m, "B")
.def(
py::init<int>(),
py::arg("b") = 2
);
py::implicitly_convertible<A, B>();
m.def("fn", &fn,
py::arg("a")
);
}
# test.py
from example import *
a = A()
b = B()
fn(b)
它构建得很好,但输出是:$ python3.9 test.py
Traceback (most recent call last):
File "/pybindtest/test.py", line 8, in <module>
fn(b)
TypeError: fn(): incompatible function arguments. The following argument types are supported:
1. (a: example.A) -> None
Invoked with: <example.B object at 0x7fc3016a83b0>
我以为我已经实现了这里描述的演示案例:https://pybind11.readthedocs.io/en/stable/advanced/classes.html#implicit-conversions我还尝试将其添加到 A 的 init 中:
.def(py::init<B>())
但没有运气。我在这里错过了什么?
提前致谢!
解决方案:
原来它必须是
py::implicitly_convertible<B, A>();
(所以 A 和 B 交换了)和 .def(py::init<B>())
也是需要的。
最佳答案
您混淆了传递给 py::implicitly_convertible
的模板参数的顺序.应该是 py::implicitly_convertible<convert_from, convert_to>
,在你的情况下应该是
py::implicitly_convertible<B, A>
关于implicit-conversion - pybind11 implicitly_convertible 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70000680/