Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

JNI: returning Byte Array from C++ to java

4,000 views
Skip to first unread message

Pascal

unread,
Jan 15, 2003, 9:22:18 AM1/15/03
to
Hi,

I implemented a method on the C++ side in some wrapper class, that reuses C++ code:

JNIEXPORT jbyteArray JNICALL Java_com_gds_jni_WvsNachricht_getWvsNachrichtAsBuffer
(JNIEnv * env, jobject obj, jlong ll_pointer){

// Get the WvsNachricht C++ Object from pointer value
WvsNachricht* lo_wvsNachrichtPtr = (WvsNachricht*) ll_pointer;

// Make a new SGZGdsBuffer Object
SGZGdsBuffer lo_buffer = lo_wvsNachrichtPtr->asBuffer();

// get the length
unsigned long ll_size = lo_buffer.size();

//extract the data
void* lo_bytePointer = (void*)lo_buffer.data();


jbyteArray lo_byteArray = env->NewByteArray(ll_size);

// copy the contents of the buffer to the jbyteArray
if (lo_byteArray){
memcpy( (void*)lo_byteArray, lo_bytePointer, ll_size);
}

return lo_byteArray;
}

void* lo_bytePointer is a buffer, that stores bytes with a size of ll_size.
Problem:
Everytime I call the JNI Funtion JVM crashes with EXCEPTION_ACCESS_VIOLATION.
I suppose the bug is in the line memcpy( (void*) ...
Is there a smarter way of returning a jbyteArray or does anybody find my bug?

Thanks a million,

Pascal

Gordon Beaton

unread,
Jan 15, 2003, 9:43:52 AM1/15/03
to
On 15 Jan 2003 06:22:18 -0800, Pascal wrote:
> Problem:
> Everytime I call the JNI Funtion JVM crashes with
> EXCEPTION_ACCESS_VIOLATION.
> I suppose the bug is in the line memcpy( (void*) ...

Yes, you shouldn't use memcpy() on a jByteArray. NewByteArray() does
*not* return a C or C++ array, it returns a java object.

You must use an accessor function such as SetByteArrayRegion() to fill
in the values.

Or use GetByteArrayElements(lo_byteArray) to get a native array that
you *can* fill in with memcpy(), then use ReleaseByteArrayElements()
to update the jbyteArray with the new values.

/gordon

--
[ do not send me private copies of your followups ]
g o r d o n . b e a t o n @ e r i c s s o n . c o m

Pascal

unread,
Jan 16, 2003, 1:55:49 PM1/16/03
to
Gordon,

thank you so much -> your hint helped me to fix the bug!

cheers,

Pascal

Gordon Beaton <n...@for.email> wrote in message news:<b03s38$bq3$1...@news.du.uab.ericsson.se>...

0 new messages