Skip to content

Convert py::object Numpy array to py::array #1310

Description

@kohr-h

I'm playing around with embedding the interpreter, and I'd like to access a Numpy array stored in a py::object using pybind11's array handling functionality, and possibly hand it off to other code.

Here's a minimal example:

#include <pybind11/embed.h>
namespace py = pybind11;

int main() {
    py::scoped_interpreter guard{};
    py::object np = py::module::import("numpy");
    py::object arr = np.attr("ones")(3);
    // want it as py::array object now and call C++ functions on it
}

Here probably my ignorance of C++ shows, but how is this conversion done? Is there functionality for that in pybind11?

A follow-up on that question would then be: Can I stop the interpreter from deleting the object when the interpreter goes out of scope? If not, or if it requires too much hacking, I'd be okay with a copy.

If there's an elegant solution, I think it would be a nice addition to the docs on embedding the interpreter.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions