在 JNI 中,从 jobject
获取字段值(如 userId
和 userName
)并将其转换为 C 风格的字符串(char*
)的过程如下:
- 首先,你需要获取对应字段的值。
- 然后,使用
GetStringUTFChars()
方法将这些值转换为 UTF-8 编码的字符数组。
下面是你的代码示例中如何完成这个操作的详细步骤:
#include <jni.h>
JNIEXPORT jint JNICALL Java_com_iroad_yuedong_station_yolo_RknnWrapper_registerFace(JNIEnv *env, jclass,
jbyteArray in,
jlong imageSize,
jobject user,
jint bFrom) {
// Step 1: Copy the input byte array.
jboolean inputCopy = JNI_FALSE;
jbyte* inData = env->GetByteArrayElements(in, &inputCopy);
// Step 2: Get the User class and field IDs for userId and userName.
jclass userCls = env->GetObjectClass(user); // Obtain the User class reference
if (userCls == nullptr) {
return -1; // Handle error
}
jfieldID userFId = env->GetFieldID(userCls, "userId", "Ljava/lang/String;");
jfieldID userNameFId = env->GetFieldID(userCls, "userName", "Ljava/lang/String;");
if (userFId == nullptr || userNameFId == nullptr) {
return -1; // Handle error
}
// Step 3: Get the values of userId and userName as jobjects.
jstring userIdObj = static_cast<jstring>(env->GetObjectField(user, userFId));
jstring userNameObj = static_cast<jstring>(env->GetObjectField(user, userNameFId));
// Step 4: Convert these jstrings to const char* using GetStringUTFChars().
const char *userIdStr = env->GetStringUTFChars(userIdObj, nullptr);
const char *userNameStr = env->GetStringUTFChars(userNameObj, nullptr);
// Do something with the strings...
// Step 5: Release resources.
env->ReleaseStringUTFChars(userIdObj, userIdStr);
env->ReleaseStringUTFChars(userNameObj, userNameStr);
// Don't forget to release inData if you are done with it and didn't use it:
env->ReleaseByteArrayElements(in, inData, JNI_ABORT);
return 0;
}
注意事项:
错误处理:请务必检查每个步骤是否成功,尤其是在获取类和字段 ID 时。如果返回
nullptr
,则表示出现了问题,可以相应地处理错误。内存管理:使用
GetStringUTFChars()
后,必须调用ReleaseStringUTFChars()
来释放分配给 C 字符串的内存,以避免内存泄漏。类型转换:当从对象中获取字符串时,需要使用类型转换 (
static_cast<jstring>
) 将返回值强制转换为正确的类型。
以上就是如何从 jobject
中获取 userId
和 userName
的详细步骤,希望对你有帮助!
内容由零声教学AI助手提供,问题来源于学员提问