如何调用使用JNI从C返回String的Java方法?
有没有办法调用java方法,它在C中返回一个String
?
对于Integer
它的工作原理如下:
JNIEXPORT jint JNICALL Java_Client_getAgeC(JNIEnv *env, jobject callingObject, jobject employeeObject) { jclass employeeClass = (*env)->GetObjectClass(env, employeeObject); jmethodID midGetAge = (*env)->GetMethodID(env, employeeClass, "getAge", "()I"); int age = (*env)->CallIntMethod(env, employeeObject, midGetAge); return age; }
我已经搜索了很长时间但是没有什么能用于String
。 最后,我想得到一个char*
提前致谢!
下面是一个JNI代码调用返回字符串的方法的示例。 希望这可以帮助。
int EXT_REF Java_JNITest_CallJava( JNIEnv* i_pjenv, jobject i_jobject ) { jclass jcSystem; jmethodID jmidGetProperty; LPWSTR wszPropName = L"java.version"; jcSystem = i_pjenv->FindClass("java/lang/System"); if(NULL == jcSystem) { return -1; } jmidGetProperty = i_pjenv->GetStaticMethodID(jcSystem, "getProperty", "(Ljava/lang/String;)Ljava/lang/String;"); if(NULL == jmidGetProperty) { return -1; } jstring joStringPropName = i_pjenv->NewString((const jchar*)wszPropName, wcslen(wszPropName)); jstring joStringPropVal = (jstring)i_pjenv->CallStaticObjectMethod(jcSystem, jmidGetProperty, (jstring)joStringPropName); const jchar* jcVal = i_pjenv->GetStringChars(joStringPropVal, JNI_FALSE); printf("%ws = %ws\n", wszPropName, jcVal); i_pjenv->ReleaseStringChars(joStringPropVal, jcVal); return 0; }
在Java中,定义本机方法
public class Client { public static native getVorname(int employeeNumber); }
这是C面:
Employee employees[100]; JNIEXPORT jstring JNICALL Java_Client_getVorname(JNIEnv *env, jclass clientClass, jint employeeNumber) { if (employeeNumber < 0 || employeeNumber > 100) { return NULL; } Employee* ptr = employees[employeeNumber]; return (*env)->NewStringUTF(env, ptr->vorname); }