您的位置:首页 > 编程语言 > Java开发

JNI——实现Java与C的协同工作(五)

2014-01-15 02:11 190 查看

第五部分 JNI的进化——JNA

JNA 的前世今生

1. Wikipedia(en) 的介绍

Java Native Access provides Java programs easy access to nativeshared
libraries without using the Java Native Interface. JNA's design aims to provide native access in a natural way with a minimum of effort.
No boilerplate or generated glue code is required.

PS:鉴于官方的说明比较啰嗦,就没有引用。

2.个人理解

简单来说,JNA 已经帮我们搞定了常用 C 中函数(甚至还有其他语言)的 JNI 链接,并封装成JAR形式的包供我们直接调用。可以说,这对于一般应用来讲是非常方便的,当然,对于那些需要我们自定义的底层函数还是要老老实实地走 JNI 的流程。

JNA 的使用

1. 获取 JNA

官方网站(GitHub):https://github.com/twall/jna

2. 将 JNA 的 JAR 包导入工程



3. 编写程序 HelloWorld.java (来自 JNA 的示例)

import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;

/** Simple example of JNA interface mapping and usage. */
public class HelloWorld {

// This is the standard, stable way of mapping, which supports extensive
// customization and mapping of Java to native types.

public interface CLibrary extends Library { // 这是JNA已经封装好的方法,可实现C中的printf
CLibrary INSTANCE = (CLibrary)
Native.loadLibrary((Platform.isWindows() ? "msvcrt" : "c"),
CLibrary.class);

void printf(String format, Object... args);
}

public static void main(String[] args) {
CLibrary.INSTANCE.printf("Welcome to JNA world!\n"); // 相当于C中的printf函数
for (int i=0;i < args.length;i++) {
CLibrary.INSTANCE.printf("Argument %d: %s\n", i, args[i]);
}
}
}


4. 编译运行

结果如下:

Welcome to JNA world!

更多 JNA 使用说明

参考官方文档:http://twall.github.io/jna/4.0/javadoc

JNI 与 JNA 性能比较

参考这篇文章:http://blog.csdn.net/drifterj/article/details/7841810
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: