Skip to content

Commit

Permalink
Add Python bindings to access the underlying buffer of a MemoryStream
Browse files Browse the repository at this point in the history
  • Loading branch information
dvicini authored and njroussel committed Apr 17, 2023
1 parent 5b784db commit 216dd0c
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 2 deletions.
3 changes: 3 additions & 0 deletions include/mitsuba/core/mstream.h
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,9 @@ class MI_EXPORT_LIB MemoryStream : public Stream {
/// Return whether or not the memory stream owns the underlying buffer
bool owns_buffer() const { return m_owns_buffer; }

/// Return the underlying raw byte array
const uint8_t *raw_buffer() const { return m_data; }

//! @}
// =========================================================================

Expand Down
5 changes: 4 additions & 1 deletion src/core/python/stream.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,10 @@ MI_PY_EXPORT(MemoryStream) {
.def(py::init<size_t>(), D(MemoryStream, MemoryStream),
"capacity"_a = 512)
.def_method(MemoryStream, capacity)
.def_method(MemoryStream, owns_buffer);
.def_method(MemoryStream, owns_buffer)
.def("raw_buffer", [](MemoryStream &s) -> py::bytes {
return py::bytes(reinterpret_cast<const char*>(s.raw_buffer()), s.size());
});
}

MI_PY_EXPORT(ZStream) {
Expand Down
5 changes: 4 additions & 1 deletion src/core/tests/test_stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,9 +213,12 @@ def test07_memory_stream():
assert s.can_write()
assert s.can_read()

s.write_string('hello world')
string = 'hello world'
s.set_byte_order(Stream.EBigEndian)
s.write_string(string)

reference = int(len(string)).to_bytes(4, 'big') + bytes(string, encoding='ascii')
assert s.raw_buffer() == reference
assert str(s) == """MemoryStream[
host_byte_order = little-endian,
byte_order = big-endian,
Expand Down

0 comments on commit 216dd0c

Please sign in to comment.