| 773 | } |
| 774 | |
| 775 | PyObject* ndarray_wrap(ndarray_handle* th, int framework, return_value_policy policy) noexcept |
| 776 | { |
| 777 | if (!th) |
| 778 | return none().release().ptr(); |
| 779 | |
| 780 | bool copy = policy == return_value_policy::copy || policy == return_value_policy::move; |
| 781 | |
| 782 | if ((ndarray_framework)framework == ndarray_framework::numpy) |
| 783 | { |
| 784 | try |
| 785 | { |
| 786 | // BACKPORT |
| 787 | // object o = steal(PyType_GenericAlloc(internals_get().nb_ndarray, 0)); |
| 788 | object o = reinterpret_steal<object>(PyType_GenericAlloc(nb_internals::get().nb_ndarray, 0)); |
| 789 | // if (!o.is_valid()) |
| 790 | if (!o) |
| 791 | return nullptr; |
| 792 | ((nb_ndarray*)o.ptr())->th = th; |
| 793 | ndarray_inc_ref(th); |
| 794 | |
| 795 | return module_::import("numpy").attr("array")(o, arg("copy") = copy).release().ptr(); |
| 796 | } |
| 797 | catch (const std::exception& e) |
| 798 | { |
| 799 | PyErr_Format( |
| 800 | PyExc_RuntimeError, |
| 801 | "pybind11::detail::ndarray_wrap(): could not " |
| 802 | "convert ndarray to NumPy array: %s", |
| 803 | e.what() |
| 804 | ); |
| 805 | return nullptr; |
| 806 | } |
| 807 | } |
| 808 | |
| 809 | object package; |
| 810 | try |
| 811 | { |
| 812 | switch ((ndarray_framework)framework) |
| 813 | { |
| 814 | case ndarray_framework::none: |
| 815 | break; |
| 816 | |
| 817 | case ndarray_framework::pytorch: |
| 818 | package = module_::import("torch.utils.dlpack"); |
| 819 | break; |
| 820 | |
| 821 | case ndarray_framework::tensorflow: |
| 822 | package = module_::import("tensorflow.experimental.dlpack"); |
| 823 | break; |
| 824 | |
| 825 | case ndarray_framework::jax: |
| 826 | package = module_::import("jax.dlpack"); |
| 827 | break; |
| 828 | |
| 829 | default: |
| 830 | pybind11_fail( |
| 831 | "pybind11::detail::ndarray_wrap(): unknown framework " |
| 832 | "specified!" |