Using memory allocated by sun.misc.Unsafe.allocateMemory () in native code

I am trying to allocate memory using sun.misc.Unsafe.allocateMemory () and access it in native code.

however, it seems that the long value returned by allocateMemory does not quite work as the right address in the C code.

Unsafe unsafe = getUnsafe(); long address = unsafe.allocateMemory(64); for (int i = 0; i < 64; i += 8) unsafe.putByte(memory + i, (byte) 0xFF); nativeMethod(address); 

However, in my native code, when I try to access the "address" as a pointer, it does not work :(

Update:. I added an image showing this problem. I passed the "address" to the native code, however, checking the memory in this place does not show the 0xFF value that I put there.

Image: http://i.stack.imgur.com/KoIYG.png

enter image description here

+4
source share
1 answer

I think it works great! Your for for loop sets every eighth byte to 0xff , and if you look closely at the display and count, you will see that every eighth byte is 0xff . There are some more random values, because Unsafe. allocateMemory() Unsafe. allocateMemory() does not return zeroed memory; it returns uninitialized memory, like C malloc() .

If you changed "i + = 8" to "i ++", then each byte will be 0xff ; it would be advisable to do this experiment to prove that it works.

+10
source

Source: https://habr.com/ru/post/1396969/


All Articles