Skip to content

[FEAT] Get a read-only view of the data in py::bytes #2517

Open
@anordal

Description

@anordal

Looking at the pybind11::bytes class (in pytypes.h), it is not obvious how to get the data out without first making an unnecessary std::string copy of it.

This function is not terribly useful:

operator std::string() const {
    char *buffer;
    ssize_t length;
    if (PYBIND11_BYTES_AS_STRING_AND_SIZE(m_ptr, &buffer, &length))
        pybind11_fail("Unable to extract bytes contents!");
    return std::string(buffer, (size_t) length);
}

More useful:

operator byte_view() const {
    char *buffer;
    ssize_t length;
    if (PYBIND11_BYTES_AS_STRING_AND_SIZE(m_ptr, &buffer, &length))
        pybind11_fail("Unable to extract contents of bytes object!");
    return { as_unsigned(buffer), as_unsigned(length) };
}
// Boiler plate
using byte_view = std::basic_string_view<uint8_t>;
size_t as_unsigned(ssize_t val) { return static_cast<size_t>(val); }
const uint8_t *as_unsigned(const char *s) { return reinterpret_cast<const uint8_t *>(s); }

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