I am trying to allocate memory using sun.misc.Unsafe.allocateMemory() and access it in native code.
however, it seems the long value returned by allocateMemory doesn't quite work as the right address in 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 'address' as a pointer, it doesn't work :(
Update: I have attached an image showing the issue. I passed the 'address' to the native code, however, examining the memory at that location doesnt show the 0xFF values I put in there.
Image: http://i.stack.imgur.com/KoIYG.png
I think it's working perfectly fine! Your "for" loop sets every eighth byte to 0xff
, and if you look closely at the display and count, you'll see that every eighth byte is 0xff
. There are some other random values in there because Unsafe. allocateMemory()
doesn't return zeroed memory; it returns uninitialized memory, just like C's malloc()
.
If you changed that "i += 8" to just "i++", then every byte would be 0xff
; it'd be worth doing that experiment to prove to yourself that it's working.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With