Search code examples
javacjava-native-interfacejnanative-code

Allow native code to directly access objects in java heap?


I have an array of objects in Java and I want to allow native C code direct access to that array (no copying or accessor functions). Is this possible? I don't mind if the solution is JVM-specific.


Solution

  • I finally found an answer. It is generally not possible to do what I wanted with JNI. However, some VMs provide the needed functionality, I used JikesRVM:

    1) The native code needs the memory location of the array. This can be achieved using the 'Magic' facility in JikesRVM, it provides an ObjectReference and an Address class that allow to obtain a memory address for each object. This address can then be forwarded to the native code as long/int argument (using JNI) and there casted to a pointer.

    2) The GC may not move objects around. This is a bit more tricky since it requires support for pinning in the GC. In the case of JikesRVM, objects can be annotated with @NonMoving and @NonMovingAllocation (also part of 'Magic'). Furthermore, objects (i.e. arrays) > 8KB are placed in a Large Object Space, which doesn't move objects around.