简体   繁体   中英

How to move data from java InputStream to a char * in c++ with jni?

How can I move the data stored in a java InputStream to a char * in c++ using JNI?

Thanks, Carlos.

This is the java code

InputStream is = new FileInputStream("filename");

int numBytesToRead = 1024;
byte[] inBuffer = new byte[numBytesToRead];
int bytesRead = is.read(inBuffer, 0, numBytesToRead);

decodeAacBytes(inBuffer, bytesRead);

and the jni code is

jint Java_com_example_test_MainActivity_decodeAacBytes(JNIEnv * env, jobject this, jbyteArray input, jint numBytes)
{
    //copy bytes from java
    jbyte* bufferPtr = (*env)->GetByteArrayElements(env, input, NULL);
    char *inputBytes = malloc(numBytes * sizeof(char));
    memcpy(inputBytes, bufferPtr, numBytes);
    (*env)->ReleaseByteArrayElements(env, input, bufferPtr, 0);

    return 0;
}

The values will now be in the inputBytes array

I do not know if you can pass an object like InputStream to JNI, but you can pass a String.

The trick would be getting the char[] in Java, before making the JNI call. You can copy the contents of the InputStream to a ByteArrayOutputStream, get the byte[] from the ByteArrayOutputStream and create the String from the byte[].

It is not possible. Here is how I found out:

jclass x = env->FindClass("java/io/InpuStream");
jclass y = env->FindClass("java/util/BitSet"); 

The above are C++ code behind. When I traced, x is NULL whereas y isn't. Therefore, an InputStream could not be materialized in a C++ JNI code. But a BitSet can be. I know because I have been using it.

From java:

{
        InputStream inputStream = rcvStream;

        byte[]  inData      = new byte[1024];
        int     bytesRead   = inputStream.read();
        byte[]  actualData  = new byte[bytesRead];
        System.arraycopy(inData, 0, actualData, 0, bytesRead);

        jni.setByteArray(inData, bytesRead);
}

From C:

{

JNIEXPORT jbyteArray JNICALL Java_org_alok_jni_AlokJNI_setByteArray
  (JNIEnv * env, jclass this1, jbyteArray ba, jint len) {
memcpy(my_char_array, ba, len);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM