Skip to content

How to interpret/expose a C++ raw memory as a numpy array *view* in Python? #2271

Closed
@ShuhuaGao

Description

@ShuhuaGao

This is a question or more likey a feature request.

Issue description

Supposing I have a block of memory in C++ (say, which may be an std::vector or a C array), how can I expose it as a numpy array to Python? More specifically, the numpy array should be a view rather than a copy of the memory, just like numpy.frombuffer or Eigen::Map.

The discussion on gitter did not yield a solution. This issue is related to #1042

Reproducible example code

According to the suggestion by @YannickJadoul on gitter, I have tried the empty py::capsule, but it did not work. A minimal example is below.

struct Group {
    int indices[5] = {1, 2, 3, 4, 5};
};

// I hope the returned py::array_t is a view that interprets memory in the C array 
py::array_t<int> get_indices(Group& g) {
    // an empty capsule
    return py::array_t<int>{5, g.indices, py::capsule{}};
}

PYBIND11_MODULE(mymodule, m) {
py::class_<Group>(m, "Group", "doc of the Group struct")
        .def(py::init<>())
        .def_property_readonly("indices", &get_indices)
        .def( // to facilitate examination of indices
            "print_indices",
            [](const Group& g) {
                py::print("The indices is now: ");
                for (auto i : g.indices) py::print(i);
            },
            "print the content of indices");
}

Test it in Python

g = mymodule.Group()
g.print_indices()  # 1 2 3 4 5
g.indices[0] = -1
g.print_indices()  # still 1 2 3 4 5

It would be great if a similar frombuffer method is available for py::array and py::array_t (without copying and without ownership), though I am not sure whether it is too difficult to do so.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions