- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在尝试调用 String.getBytes()
方法从字符串对象获取 JNI 中的字节数组。 JNI 具有返回 jbyte 的方法 CallByteMethod
、CallByteMethodV
和 CallByteMethodA
但它没有返回 java 字节数组的方法。
我尝试调用 CallByteMethod
方法,但出现错误
JNI DETECTED ERROR IN APPLICATION: use of deleted local reference 0xd5ec7fe1
我尝试的其他代码是使用像这样的 jbytearray 转换
jbyteArray keyBytes = (jbyteArray)(*env)->CallByteMethod(env, stringValue, getBytesMId);
由于IDE显示警告
Taking pointer from integer without a cast.
但后来我得到了一个不同的错误
JNI DETECTED ERROR IN APPLICATION: the return type of CallByteMethod does not match byte[] java.lang.String.getBytes()
下面是我的代码:
JNIEXPORT jstring JNICALL
Java_net_jni_test_MainActivity_callTest(JNIEnv *env, jobject instance) {
jstring stringValue = "test";
jclass stringClass = (*env)->FindClass(env, "java/lang/String");
jmethodID getBytesMId = (*env)->GetMethodID(env, stringClass, "getBytes", "()[B");
jbyteArray keyBytes = (*env)->CallByteMethod(env, stringValue, getBytesMId);
return (*env)->NewStringUTF(env, "1111");
}
最佳答案
只需从您的代码中发现一些错误:
下面一行是错误的:
jstring stringValue = "test";
它应该像下面这样:
jstring stringValue = (*env)->NewStringUTF(env, "test");
使用CallObjectMethod
获取jbyteArray
,记得将返回类型转换为jbyteArray
。见下文:
jbyteArray keyBytes = (jbyteArray)(*env)->CallObjectMethod(env, stringValue, getBytesMId);
下面是显示预期结果的屏幕截图。
完整来源:
JNIEXPORT jstring JNICALL
Java_net_jni_test_MainActivity_callTest(JNIEnv *env, jobject instance) {
jstring stringValue = (*env)->NewStringUTF(env, "test");
jclass stringClass = (*env)->FindClass(env, "java/lang/String");
jmethodID getBytesMId = (*env)->GetMethodID(env, stringClass, "getBytes", "()[B");
jbyteArray keyBytes = (jbyteArray)(*env)->CallObjectMethod(env, stringValue, getBytesMId);
// determine the needed length and allocate a buffer for it
jsize num_bytes = (*env)->GetArrayLength(env, keyBytes);
// obtain the array elements
jbyte* elements = (*env)->GetByteArrayElements(env, keyBytes, NULL);
if (!elements) {
// handle JNI error ...
}
for(int i = 0; i < num_bytes; i++) {
char ch = elements[i];
ALOGI("arrayLength: %c", ch);
}
// Do not forget to release the element array provided by JNI:
(*env)->ReleaseByteArrayElements(env, keyBytes, elements, JNI_ABORT);
}
请注意 C++ JNI 和 C JNI 的区别。例如。 C 风格的 JNI 有以下方法约定:
jmethodID getBytesMId = (*env)->GetMethodID(env, stringClass, "getBytes", "()[B");
但是C++是这样的:
jmethodID getBytesMId = env->GetMethodID(stringClass, "getBytes", "()[B");
关于java - 如何在 JNI 中调用 String.getBytes()?我想在 JNI 中获取字节数组,但 CallByteMethod 只返回 jbyte 而不是 jbytearray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54413047/
使用登录后,我想吐出用户名。 但是,当我尝试单击登录按钮时, 它给了我力量。 我看着logcat,但是什么也没显示。 这种编码是在说。 它将根据我在登录屏幕中输入的名称来烘烤用户名。 不会有任何密码。
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 这个问题似乎是题外话,因为它缺乏足够的信息来诊断问题。 更详细地描述您的问题或include a min
我是一名优秀的程序员,十分优秀!