Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using sun.misc.Unsafe to get address of Java array items?

I'm struggling to understand the documentation of sun.misc.Unsafe -- I guess as it's not intended for general use, nobody's really bothered with making it readable -- but I actually really need a way to find the address of an element in an array (so that I can pass a pointer to it to native code). Has anyone got any working code that does this? Is it reliable?

like image 976
Jules Avatar asked Oct 28 '11 20:10

Jules


1 Answers

Instead of using an array you can use a ByteBuffer.allocateDirect() direct buffer. This has the address in a field and this address doesn't change for the life of the ByteBuffer. A direct ByteBuffer uses minimal heap space. You can get the address using reflection.


You can use Unsafe to get an address, the problem is that the GC can move it at any time. Objects are not fixed in memory.

In JNI you can use special methods to copy data to/from Java objects to avoid this issue (and others) I suggest you use these if you want to exchange data between Objects with C code.

like image 172
Peter Lawrey Avatar answered Oct 28 '22 09:10

Peter Lawrey