8000 Use bytearray instead of bytes · scijava/scyjava@f06fa5d · GitHub
[go: up one dir, main page]

Skip to content

Commit f06fa5d

Browse files
committed
Use bytearray instead of bytes
Use a bytearray instead of bytes for the Java array data buffer. A bytearray is mutable, thus wrapping a bytearray with np.frombuffer() returns a numpy array with read/write access.
1 parent cb73716 commit f06fa5d

File tree

1 file changed

+10
-1
lines changed

1 file changed

+10
-1
lines changed

src/scyjava/_convert.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -615,7 +615,16 @@ def _jarray_to_ndarray(jarr):
615615
}
616616
# fmt: on
617617
dtype = jarraytype_map[element_type]
618-
bb = bytes(jarr)
618+
# Use a bytearray instead of memoryview for np.frombuffer.
619+
# Casting memoryview() on a Java array copies the array's content
620+
# into a buffer which does not get released when a new view is
621+
# requested. If the Java array's data changes a new memoryview will
622+
# contain the old buffer data. The view and any object created with
623+
# it must be deleted (del or =None) to release the buffer before
624+
# requesting a new view. Instead of utilizing the buffer
625+
# memoryview creates of the Java array, we obtain the buffer ouselves
626+
# as a mutable bytearray.
627+
bb = bytearray(jarr)
619628
ndarray = np.frombuffer(bb, dtype=dtype)
620629
del bb # release the buffer
621630
return ndarray.reshape(_jarray_shape(jarr))

0 commit comments

Comments
 (0)
0