3. 带有字符串参数的本地方法:
JNI中提供了一组C语言的函数用于帮助在Java和C之间传递字符串数据,下面的代码会给出详细的注释说明。
1) 编写带有native方法的Java代码:
1 public class Printf {
2 public static native int print(String format,double x);
3 static {
4 System.loadLibrary(\"Printf\");
5 }
6 }
2) 编写与native方法对应的C语言代码:
1 #include \"Printf.h\"
2 #include <stdlib.h>
3 #include <string.h>
4 #include <float.h>
5 JNIEXPORT jstring JNICALL Java_Printf_print
6 (JNIEnv* env, jclass cl, jstring format, jdouble x)
7 {
8 //1. 这里通过C语言调用JNI本地函数时,需要将参数env解引用之后在调用。
9 //env是指向所有JNI本地函数指针表的指针。
10 //2. 返回\"改良UTF-8\"编码的字符串的指针,或者当不能构建字符数组时返回NULL。
11 //直到RelaseStringUTFChars函数调用前,该指针一致有效。
12 //3. 由于Java针对字符串使用了对象池的技术,因此这里一定不能修改返回的const char*
13 const char* cformat = env->GetStringUTFChars(format,NULL);
14 //4. 获取参数中jstring的长度(GetStringUTFLength)
15 char* cret = (char*)calloc(env->GetStringUTFLength(format) + 20,1);
16 sprintf(cret,cformat,x);
17 //5. 根据\"改良UTF-8\"字节序列,返回一个新的Java对象,或者当字符串构造时,返回NULL。
18 jstring ret = env->NewStringUTF(cret);
19 free(cret);
20 //