Skip to Main Content

Java HotSpot Virtual Machine

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How to pass a char array pointer from JNI to Java without copying the array

918593Feb 20 2012
Hello All,

My requirement is to pass a char* (character array pointer) from JNI to Java with out actually copying the array. i.e., i want to avoid creating NewByteArray and copying elements in to this byteArray (byte by byte) and then returning the array.

I saw some documentation which says we can allocate direct buffer using NewDirectByteBuffer(). I have tried using it, but when i try to access the array from the ByteBuffer newly created, it always gives UnsupportedOperationException at java level. My code is as follows:

In Jni:

static jobject getByteBuffer(JNIEnv* env, jobject thiz)
{

gElement = gMyCppImplementation->getByteBuffer(size);// char* pointer will be returned by my C++ code and size i will fill in the getByteBuffer method
LOGE("After get bytebuffer call address %d, size %d",gElement, size);
LOGE("size of array is=%d ", (int)size);
myByteBuffer = env->NewDirectByteBuffer((void*)gElement, (jlong)size);
return myByteBuffer ;
}

In Java:

ByteBuffer converted = (ByteBuffer)getByteBuffer();

converted.isDirect() returns true but converted.hasArray() gives me unsupportedoperationexception.

Please help me how to solve this problem or any other alternative to resolve it.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 19 2012
Added on Feb 20 2012
0 comments
2,130 views