-
It seems you aren't able to implicitly cast types from a source type to a pointer of the target type: #include "nanobind/nanobind.h"
#include <cstdint>
namespace nb = nanobind;
using namespace nb::literals;
class IntWrapper {
public:
int64_t i;
IntWrapper(int64_t i) : i(i) {}
};
NB_MODULE(thing, m) {
nb::class_<IntWrapper>(m, "IntWrapper").def(nb::init_implicit<int64_t>(), "i"_a);
m.def("cast_to_value", [](nb::object obj) { return nb::cast<IntWrapper>(obj); }, "obj"_a);
m.def("cast_to_ptr", [](nb::object obj) { return nb::cast<IntWrapper *>(obj); }, "obj"_a);
} Running the following test: import thing
x, y = thing.IntWrapper(1), 1
print(f"cast IntWrapper to value: {x} -> {thing.cast_to_value(x)}")
print(f"cast IntWrapper to ptr: {x} -> {thing.cast_to_ptr(x)}")
print(f"cast int to value: {y} -> {thing.cast_to_value(y)}")
print(f"cast int to ptr: {y} -> {thing.cast_to_ptr(y)}") Results in this:
While an equivalent setup in pybind11: #include "pybind11/pybind11.h"
#include <cstdint>
namespace py = pybind11;
using namespace py::literals;
class IntWrapper {
public:
int64_t i;
IntWrapper(int64_t i) : i(i) {}
};
PYBIND11_MODULE(thing, m) {
py::class_<IntWrapper>(m, "IntWrapper").def(py::init<int64_t>(), "i"_a);
py::implicitly_convertible<int64_t, IntWrapper>();
m.def("cast_to_value", [](py::object obj) { return py::cast<IntWrapper>(obj); }, "obj"_a);
m.def("cast_to_ptr", [](py::object obj) { return py::cast<IntWrapper *>(obj); }, "obj"_a);
} seems to work fine:
I suppose since you are create a new object, ownership is more ambiguous if you return a pointer, but I don't think that is unique to implicit casting, and pybind11 seems to handle the issue fine? Is there some reason why nanobind can't handle this case? I'm not sure this is necessarily a bug, so I didn't post it under issues. But it should probably be mentioned in the porting guide section of the docs, if it's not fixable. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
This seems scary to me. What does the |
Beta Was this translation helpful? Give feedback.
This seems scary to me. What does the
cast_to_ptr
even do in pybind11? I can't imagine that this is safe to rely on.