-
Notifications
You must be signed in to change notification settings - Fork 202
Description
Sorry if this is a FAQ, but I could not find this in the documentation, hence a request to improve the documentation.
Does JArray.of(numpy_array) map the data, or copy? The documentation is not clear, but I assume it copies.
The documentation states:
NumPy arrays integrate seamlessly with JPype and allow fast, memory-efficient data transfers to Java. For example, a NumPy array can be mapped directly to a Java primitive array, enabling high-speed operations without unnecessary copying.
but there is no code example given that maps the data. Maybe this refers to the JArray.of function, but from the documentation this seems to return, e.g., double[][]; which given Java's memory layout is likely only possible with copying.
(well, if the data is row-major and has the right endianess, you could point java primitive arrays to the backing buffer, but this sounds horribly fragile with GC to not cause invalid frees?)
So assume we have some large data in the Python ecosystem, which often means in an existing numpy array.
I'd like to access this data from Java without copying (because of memory). It's fine if I need an adapter on the Java side, my code hopefully has the typing for that; even if that means I may need to implement slicing in Java. Say, I am fine with supporting dense and contiguous ndarrays only, so this will basically just boil down to offset computations into a direct buffer and potentially endianness conversions, I assume. (I understand that we will not get Java arrays from it, I am talking about buffers.)
How can we do this?
The documentation I found https://jpype.readthedocs.io/en/latest/userguide.html#buffer-backed-numpy-arrays
always creates a new buffer. Is there a way to expose an existing numpy buffer to Java without copying?
Can we simply convert the .data (and other fields of the ndarray)?
jb = jpype.nio.convertToDirectBuffer(numpyarray.data)– I could not find instructions on how to zero-copy map an existing numpy array to Java; but I'd imagine that a lot of users will be looking for this.
Thank you.