Reputation: 2586
How can I move the data stored in a java InputStream to a char * in c++ using JNI?
Thanks, Carlos.
Upvotes: 0
Views: 5839
Reputation: 4454
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.
Upvotes: -1
Reputation: 10
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);
}
Upvotes: -3
Reputation: 3322
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
Upvotes: 5
Reputation: 24885
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[].
Upvotes: 0