JNI GetStringUTFChars 函數錯誤

JDK1.7

gcc4.6 / g++4.6



$ gcc -fPIC -shared -o libMyJni.so MyJni.cpp -I. -I$JAVA_HOME/include/linux -I$JAVA_HOME/include
MyJni.cpp: In function ‘void Java_TestJni_print(JNIEnv*, jobject, jstring)’:
MyJni.cpp:15:65: error: no matching function for call to ‘JNIEnv_::GetStringUTFChars(JNIEnv*&, _jstring*&, NULL)’
MyJni.cpp:15:65: note: candidate is:
/home/jackson/Programs/jdk1.7.0_51/include/jni.h:1616:17: note: const char* JNIEnv_::GetStringUTFChars(jstring, jboolean*)
/home/jackson/Programs/jdk1.7.0_51/include/jni.h:1616:17: note:   candidate expects 2 arguments, 3 provided
MyJni.cpp:17:49: error: no matching function for call to ‘JNIEnv_::ReleaseStringUTFChars(JNIEnv*&, _jstring*&, const char*&)’
MyJni.cpp:17:49: note: candidate is:
/home/jackson/Programs/jdk1.7.0_51/include/jni.h:1619:10: note: void JNIEnv_::ReleaseStringUTFChars(jstring, const char*)
/home/jackson/Programs/jdk1.7.0_51/include/jni.h:1619:10: note:   candidate expects 2 arguments, 3 provided


意思就是:

沒有這個方法(三個參數的),只有兩個參數的方法

解決:

使用兩個參數的方法(這個*.cpp 代碼的調用)

const char* JNIEnv_::GetStringUTFChars(jstring, jboolean*)

void JNIEnv_::ReleaseStringUTFChars(jstring, const char*)


注:

這些函數使用 C 調用和用 C++ 調用,方法是不一樣的

查看 http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/design.html#wp16696中的

Native Method Arguments  這一節有舉例說明。

下邊內容爲該部分節選

#################################################################################################

The C function with the long mangled name Java_pkg_Cls_f_ILjava_lang_String_2 implements native method f:

Code Example 2-1 Implementing a Native Method Using C
jdouble Java_pkg_Cls_f__ILjava_lang_String_2 (
     JNIEnv *env,        /* interface pointer */
     jobject obj,        /* "this" pointer */
     jint i,             /* argument #1 */
     jstring s)          /* argument #2 */
{
     /* Obtain a C-copy of the Java string */
     const char *str = (*env)->GetStringUTFChars(env, s, 0);
     /* process the string */
     ...
     /* Now we are done with str */
     (*env)->ReleaseStringUTFChars(env, s, str);
     return ...
}

Note that we always manipulate Java objects using the interface pointer env . Using C++, you can write a slightly cleaner version of the code, as shown in Code Example 2-2:

Code Example 2-2 Implementing a Native Method Using C++
extern "C" /* specify the C calling convention */  

jdouble Java_pkg_Cls_f__ILjava_lang_String_2 ( 
     JNIEnv *env,        /* interface pointer */ 
     jobject obj,        /* "this" pointer */ 
     jint i,             /* argument #1 */ 
     jstring s)          /* argument #2 */ 
{ 
     const char *str = env->GetStringUTFChars(s, 0); 
     ... 
     env->ReleaseStringUTFChars(s, str); 
     return ... 
} 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章