Use sun misc. Unsafe get the address of the Java array item?
I'm trying to understand Sun misc. Unsafe's document - I think no one really bothers to make it readable because it's not suitable for general purposes - but in fact, I really need a way to find the address of an element, an array (so that I can pass pointers to native code) Does anyone have any working code to do this? Is it reliable?
Solution
You can use ByteBuffer Allocatedirect () directly buffers instead of using arrays It has the address in the field, and the address will not change during the life cycle of ByteBuffer Direct ByteBuffer uses the smallest heap space You can use reflection to get the address
You can use unsafe to get the address. The problem is that GC can move it at any time The object was not repaired in memory
In JNI, you can use special methods to copy data to or from Java objects to avoid this problem (and other problems). If you want to exchange data between objects with C code, I recommend you use these methods