-
now #include <nanobind/nanobind.h>
#include <nanobind/ndarray.h>
#include <nanobind/stl/vector.h>
namespace nb = nanobind;
NB_MODULE(myext, m) {
m.def("foo", [](nb::ndarray<> a) {
auto numpy = nb::module_::import_("numpy");
// add one dimension
std::vector<int> shape(a.shape_ptr(), a.shape_ptr() + a.ndim());
shape.insert(shape.begin(), 1);
auto b = numpy.attr("broadcast_to")(a, shape);
nb::print(b);
});
} >>> import numpy as np
>>> import myext
>>> a = np.arange(4)
>>> a
array([0, 1, 2, 3])
>>> myext.foo(a)
[[<capsule object "dltensor" at 0x7f674c492f90>
<capsule object "dltensor" at 0x7f674c492f90>
<capsule object "dltensor" at 0x7f674c492f90>
<capsule object "dltensor" at 0x7f674c492f90>]] in pybind11, equivalent #include <pybind11/numpy.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
namespace py = pybind11;
PYBIND11_MODULE(myext, m) {
m.def("foo", [](py::array a) {
auto numpy = py::module::import("numpy");
// add one dimension
std::vector<int> shape(a.shape(), a.shape() + a.ndim());
shape.insert(shape.begin(), 1);
auto b = numpy.attr("broadcast_to")(a, shape);
py::print(b);
});
} >>> import numpy as np
>>> import myext
>>> a = np.arange(4)
>>> a
array([0, 1, 2, 3])
>>> myext.foo(a)
[[0 1 2 3]] I'm curious about the design decision on making Also, would it be more convenient to stick to the underlying element instead of the |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Actually, it's a type caster in both frameworks. However, the design of |
Beta Was this translation helpful? Give feedback.
FYI, I also pushed d089d89 that fixes the issue in another way: when returning/casting a
nb::ndarray
back to python, it remembers the Python object that was originally associated with this array.