如何比较c语言中的两个jstrings。我需要这个用于jni执行,其中逻辑是用.c文件写的,用于比较两个名称
答案 0 :(得分:3)
如果你想使用纯原生:
JNIEXPORT void JNICALL Java_ClassName_MethodName(JNIEnv *env, jobject obj, jstring javaString1, jstring javaString2)
{
const char *nativeString1 = (*env)->GetStringUTFChars(env, javaString1, 0);
const char *nativeString2 = (*env)->GetStringUTFChars(env, javaString2, 0);
/* Now you can compare nativeString1 with nativeString2*/
int res = strncmp(nativeString1, nativeString2, strlen(nativeString1);
/* And don't forget to release the handles */
(*env)->ReleaseStringUTFChars(env, javaString1, nativeString1);
(*env)->ReleaseStringUTFChars(env, javaString2, nativeString2);
}
如果您想使用本机代码中的Java(与this one相同的答案,所有信用都归原作者所有):
JNIEXPORT void JNICALL Java_ClassName_MethodName(JNIEnv *env, jobject obj, jstring javaString1, jstring javaString2)
{
/* Get java class String handle */
jclass cls = (*env)->GetObjectClass(env, javaString1);
/* Get method ID equals from String handle */
jmethodID mID = (*env)->GetMethodID(env, cls, "equals", "(Ljava/lang/Object;)Z");
/* Compare both methods, store in jboolean which can be case to uint8_t or bool if you're using C99*/
jboolean equals = (*env)->CallBooleanMethod(env, javaString1, mID, javaString2);
}