This should help you. It allows a c unsigned char array to be set from Java. It uses a jshortArray instead of a jbyteArray as you can't get the full 8 bit positive number range of an unsigned char from a java byte (128 - 255 not possible). Change occurrences of byte to short if that is what you really want.
Java class:
public class example {
public final static native void set_Foo_array(long jarg0, short[] jarg1);
public final static native short[] get_Foo_array(long jarg0);
}
c++ code:
class Foo {
public:
unsigned char array[10];
};
extern "C"{
JNIEXPORT void JNICALL Java_example_set_1Foo_1array(JNIEnv *jenv, jclass jcls, jlong jarg0, jshortArray jarg1) {
Foo *arg0 ;
unsigned char *arg1 ;
int i ;
jshort* jarg1_carray ;
jsize jarg1_len = jenv->GetArrayLength(jarg1) ;
arg0 = *(Foo **)&jarg0;
jarg1_carray = jenv->GetShortArrayElements(jarg1, 0);
arg1 = (unsigned char *) malloc(jarg1_len * sizeof(unsigned char ));
for(i=0; i<jarg1_len; i++)
arg1 = (unsigned char )jarg1_carray;
{
int i;
for (i=0; i><10; i++)
arg0->array = arg1;
}
jenv->ReleaseShortArrayElements(jarg1, jarg1_carray, 0);
free(arg1);
}}
extern "C"{
JNIEXPORT jshortArray JNICALL Java_example_get_1Foo_1array(JNIEnv *jenv, jclass jcls, jlong jarg0) {
jshortArray jresult = 0 ;
Foo *arg0 ;
unsigned char *result ;
jshort* jnitype_ptr = 0 ;
int k ;
arg0 = *(Foo **)&jarg0;
result = (unsigned char *)(unsigned char *) (arg0->array);
jresult = jenv->NewShortArray(10);
jnitype_ptr = jenv->GetShortArrayElements(jresult, 0);
for (k=0; k<10; k++)
jnitype_ptr[k] = (jshort)result[k];
jenv->ReleaseShortArrayElements(jresult, jnitype_ptr, 0);
return jresult;
}}
The code comes from the output of swig (www.swig.org) - a tool which generated the JNI and Java code given the C++ class definition above.
for part 2 here is some code i've written that is used to load a raster (RGB) from OpenGL (a char*) to a byte[] in java.
static .. jvm; // ref to jvm
static jobject printAPI; // the static class ref
static jmethodID loadBuffer; // the static method ref
void loadImage(int x, int y, int width, int height, char* pixels, int maxWidth, int maxHeight){
JNIEnv* env;
jint result = (*jvm)->GetEnv(jvm, &env, JNI_VERSION_1_2);
if(result < 0 || env == NULL){
fprintf(stderr, "Error finding JNI environment\n");
}else{
int i, size = width*height*3;
jbyteArray rgb; // the byte array
jbyte* v; // array of jbytes for transfer operation
/* Transfer char* to jbyteArray */
rgb = (*env)->NewByteArray(env, width * height *3);
v = malloc( (width * height *3) * sizeof(jbyte));
if( !rgb || !v ){
fprintf(stderr, "Error allocating memory in loadImage(..)");
return;
}
for(i=0;i<size; ++i) v[i] = (jbyte) pixels[i];
(*env)->SetByteArrayRegion(env, rgb, 0, size, v);
/* send pixel dump to gui */
(*env)->CallStaticIntMethod(env, printAPI, loadBuffer, x, y, width, height, rgb);
}
}
the method on the java side is
static void loadByteArray( int x, int y, int w, int h, byte[] rgb ){..}
Hope it helps.