2 Replies Latest reply on Feb 27, 2004 5:26 PM by 843829

    returning byte array in JNI

      I am trying to return an array of byte from JNI to java. I read the tutorial but i still find it hard to understand.
      BYTE *encoded is the variable that has the contents to be sent back to java.
      jbytearray jb=encoded;
      ret jb;
      This does not seem to reurn anything!! Please help
        • 1. Re: returning byte array in JNI
          In java, an array is an object.

          Since you want to return an object to java, you have to

          a) use JNI to construct an array object.
          b) Fill in the array with the elements from the C array.
          • 2. Re: returning byte array in JNI
            This is the JNI implementation of the method:
            public native byte[] returnArray (int size, byte initialValue).
            JNIEXPORT jbyteArray JNICALL Java_Test_returnArray
              (JNIEnv *env, jobject This, jint size, jbyte initialValue) {
                   //-- No error handling is being done...
                   jbyte* buf = new jbyte[size];
                   memset (buf, initialValue, size);
                   jbyteArray ret = env->NewByteArray(size);
                   env->SetByteArrayRegion (ret, 0, size, buf);
                   delete[] buf;
                   return ret;
            A jbyte is a signed char (a signed byte). You can mix signed bytes and unsigned bytes in C++ depending on your needs. This JNI method is the functional equivalent of the 100% Java function:
            public byte[] returnArray (int size, byte initialValue) {
                byte[] ret = new byte[size];
                for (int i = 0; i < size; ++i) {
                    ret[i] = initialValue;
                return ret;