gpt4 book ai didi

java - 如何在 JNI 中调用 String.getBytes()?我想在 JNI 中获取字节数组,但 CallByteMethod 只返回 jbyte 而不是 jbytearray

转载 作者:搜寻专家 更新时间:2023-11-01 09:21:54 24 4
gpt4 key购买 nike

我正在尝试调用 String.getBytes() 方法从字符串对象获取 JNI 中的字节数组。 JNI 具有返回 jbyte 的方法 CallByteMethodCallByteMethodVCallByteMethodA 但它没有返回 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");
}

最佳答案

只需从您的代码中发现一些错误:

  1. 下面一行是错误的:

    jstring stringValue = "test";

    它应该像下面这样:

    jstring stringValue = (*env)->NewStringUTF(env, "test");
  2. 使用CallObjectMethod获取jbyteArray,记得将返回类型转换为jbyteArray。见下文:

    jbyteArray keyBytes = (jbyteArray)(*env)->CallObjectMethod(env, stringValue, getBytesMId);
  3. 下面是显示预期结果的屏幕截图。

    enter image description here

完整来源:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com