This discussion is archived
0 Replies Latest reply: Feb 20, 2012 12:38 AM by 918593 RSS

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

918593 Newbie
Currently Being Moderated
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.

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points