[英]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?如何使用 JNI 将存储在 java InputStream 中的数据移动到 c++ 中的 char *?
Thanks, Carlos.谢谢,卡洛斯。
This is the java code这是 java 代码
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 jni代码是
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这些值现在将位于 inputBytes 数组中
I do not know if you can pass an object like InputStream to JNI, but you can pass a String.我不知道你是否可以将 object 之类的 InputStream 传递给 JNI,但你可以传递一个字符串。
The trick would be getting the char[] in Java, before making the JNI call.诀窍是在进行 JNI 调用之前获取 Java 中的 char[]。 You can copy the contents of the InputStream to a ByteArrayOutputStream, get the byte[] from the ByteArrayOutputStream and create the String from the byte[].您可以将 InputStream 的内容复制到 ByteArrayOutputStream,从 ByteArrayOutputStream 获取 byte[] 并从 byte[] 创建 String。
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.以上是C++
后面的代码。 When I traced, x
is NULL
whereas y
isn't.当我追踪时, x
是NULL
而y
不是。 Therefore, an InputStream
could not be materialized in a C++
JNI
code.因此,无法在C++
JNI
代码中具体化InputStream
。 But a BitSet
can be.但是BitSet
可以。 I know because I have been using it.我知道,因为我一直在使用它。
From java:来自 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:来自 C:
{
JNIEXPORT jbyteArray JNICALL Java_org_alok_jni_AlokJNI_setByteArray
(JNIEnv * env, jclass this1, jbyteArray ba, jint len) {
memcpy(my_char_array, ba, len);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.