Linux安全网 - Linux操作系统_Linux 命令_Linux教程_Linux黑客

会员投稿 投稿指南 本期推荐:
搜索:
您的位置: Linux安全网 > Linux编程 > » 正文

Step By Step(Java 本地方法篇)(3)

来源: 未知 分享至:
class MyTest {
3 public static void main(String[] args) throws Exception {
4 int count = Printf.print(8,4,3.14);
5 count += Printf.print(8,4,count);
6 System.out.println();
7 for (int i = 0; i < count; ++i) {
8 System.out.print(\"-\");
9 }
10 System.out.println();
11 }
12 }
13 /* 输出结果如下:
14 3.1400 8.0000
15 ----------------
16 */

    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 //

Tags:
分享至:
最新图文资讯
1 2 3 4 5 6
验证码:点击我更换图片 理智评论文明上网,拒绝恶意谩骂 用户名:
关于我们 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 发展历史