pybind11 implicitly_convertible 不起作用

pybind11 implicitly_convertible does not work

我正在努力使最简单的示例起作用。这是我的代码:

// 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>