Skip to content

Marking a pybind11::array as read-only #481

Closed
@stukowski

Description

@stukowski

The method pybind11::array::writeable() tells whether the array's data is mutable. It would be nice to have a corresponding method for marking the data in an array as read-only. Unless I overlooked something, it seems the only way to do this is with a hack like this:

const double* data = ...
size_t num_elements = ...

py::array_t<double> array({ num_elements }, data);

reinterpret_cast<py::detail::PyArray_Proxy*>(array.ptr())->flags &= ~py::detail::npy_api::NPY_ARRAY_WRITEABLE_;

My suggestion is to add a method to the pybind11::array class that allows modifying the array flags (either all or specifically the writable flag).

Background: I would like to implement a getter method binding that returns a NumPy array pointing to an internal C++ data buffer (without making a copy of the data). The Python side should not be able to modify the data, so I would like to mark the array as read-only.

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