Wednesday, April 24, 2013

jni jnienv GetDirectBufferAddress example c c++ java


GetDirectBufferAddress

void* GetDirectBufferAddress(JNIEnv* env, jobject buf);
Fetches and returns the starting address of the memory region referenced by the given direct java.nio.Buffer.(GetDirectBufferAddress)
This function allows native code to access the same memory region that is accessible to Java code via the buffer object.
LINKAGE:
Index 230 in the JNIEnv interface function table.
PARAMETERS of GetDirectBufferAddress
env: the JNIEnv interface pointer
buf: a direct java.nio.Buffer object (must not be NULL)
RETURNS of GetDirectBufferAddress
Returns the starting address of the memory region referenced by the buffer. Returns NULL if the memory region is undefined, if the given object is not a direct java.nio.Buffer, or if JNI access to direct buffers is not supported by this virtual machine.
Example of GetDirectBufferAddress
JNIEXPORT jobject JNICALL Java_com_foo_allocNativeBuffer(JNIEnv* env, jobject thiz, jlong size)
{
    void* buffer = malloc(size);
    jobject directBuffer = env->NewDirectByteBuffer(buffer, size);
    jobject globalRef = env->NewGlobalRef(directBuffer);

    return globalRef;
}

JNIEXPORT void JNICALL Java_comfoo_freeNativeBuffer(JNIEnv* env, jobject thiz, jobject globalRef)
{
    void *buffer = env->GetDirectBufferAddress(globalRef);

    env->DeleteGlobalRef(globalRef);
    free(buffer);
}
Then in Java...
mImageData = (ByteBuffer)allocNativeBuffer( mResX * mResY * mBPP );
and
freeNativeBuffer(mImageData);
mImageData = null;