Jeff Storey
Jeff Storey

Reputation: 57202

JNI unsigned char to byte array

I'm working with a C++ library that stores image byte data in an array of unsigned characters. My jni function returns a jByteArray (which then gets converted to a BufferedImage on the java side), but I'm not sure how to fill the jByteArray from the unsigned character array (if it is possible). Can anyone provide a snippet for this last part to basically do this:

// size is the size of the unsigned char array
const int size = 100;
unsigned char* buf = new unsigned char[size];
// buf gets passed to another library here to be populated

jbyteArray bArray = env->NewByteArray(size);
// now how do I get the data from buf to bArray?

Thanks, Jeff

Upvotes: 2

Views: 10299

Answers (2)

Asif Rafiq
Asif Rafiq

Reputation: 291

User jbyte* instead of unsigned char*

In JNI A jbyte is defined to be a signed char. JNI offers a few functions for that purpose: you can create a new jbyteArray and set a specified region of it given a jbyte* buffer.

Please Read the documentation.

Upvotes: 1

bmargulies
bmargulies

Reputation: 100113

Here's a snippet that should point you in the right direction.

jboolean isCopy;
void *data = env->GetPrimitiveArrayCritical((jarray)bArray, &isCopy);

memcpy(data, buf, bytecount);

// and don't forget the 'release'

Upvotes: 3

Related Questions