https://github.com/twall/jna
目前版本: 4.1.0
先看一个简单的例子:调用Windows API的printf输出“Hello, World”。
JNA代码:
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;
public class HelloWorld1 {
public interface CLibrary extends Library {
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("Hello, World\n");
}
}
第6行定义CLibrary映射到Native(继承JNA的Library)
第7,8行加载目标Native Lib(Windows:msvcrt.dll,也可以是自己的so或dll)
第10行映射Native方法
第14行作为Java的普通方法调用printf
这是一种静态的映射方法,以下也可以动态映射:
import com.sun.jna.Function;
import com.sun.jna.Platform;
public class HelloWorld2 {
public static void main(String[] args) {
String libraryName = Platform.isWindows() ? "msvcrt" : "c";
String functionName = "printf";
// Function
Function function = Function.getFunction(
libraryName,
functionName,
Function.C_CONVENTION);
// Invoke
function.invoke(new Object[]{"Hello, world\n"});
}
}
JNI来实现调用C写的方法:
1)编写HelloWorld.java
/* HelloWorld.java */
public class HelloWorld {
public native void hello(); /* (1) */
static {
System.loadLibrary("helloworld"); /* (2) */
}
public static void main (String args[]) {
HelloWorld h = new HelloWorld();
h.hello(); /* (3) */
}
}
2)编译java文件
引用
/usr/java/jdk1.7.0_45/bin/javac HelloWorld.java
3)生成JNI的HelloWorld.h
引用
/usr/java/jdk1.7.0_45/bin/javah -jni HelloWorld
/* DO NOT EDIT THIS FILE - it is machine generated */
#include
/* Header for class HelloWorld */
#ifndef _Included_HelloWorld
#define _Included_HelloWorld
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: HelloWorld
* Method: hello
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_HelloWorld_hello
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
4)编写HelloWorld.c
#include "HelloWorld.h"
JNIEXPORT void JNICALL Java_HelloWorld_hello
(JNIEnv *env, jobject me)
{
printf("Hello World\n");
}
5)编译HelloWorld.c
引用
gcc -fPIC -shared HelloWorld.c -I/usr/java/jdk1.7.0_45/include/ -I/usr/java/jdk1.7.0_45/include/linux/ -o libhelloworld.so
6)执行HelloWorld
引用
java -Djava.library.path=. HelloWorld
JNA来实现调用C写的方法:
1)编写hello.c
#include
void hello ()
{
printf("Hello World!\n");
}
2)编译hello.c
引用
gcc -fPIC -shared -o libhello.so hello.c
3)编写HelloJNA.java
import com.sun.jna.Library;
import com.sun.jna.Native;
interface HelloLib extends Library {
HelloLib INSTANCE = (HelloLib) Native.loadLibrary("hello", HelloLib.class);
void hello();
}
public class HelloJNA {
public static void main(String[] args){
HelloLib hello = HelloLib.INSTANCE;
hello.hello();
}
}
4)编译执行
引用
javac -cp jna-4.1.0.jar HelloJNA.java
java -cp .:jna-4.1.0.jar HelloJNA
参考:
http://en.wikipedia.org/wiki/Java_Native_Access
http://en.wikipedia.org/wiki/Java_Native_Interface
http://en.wikipedia.org/wiki/SWIG
http://www.swig.org/
http://en.wikipedia.org/wiki/Platform_Invocation_Services
http://www.atmarkit.co.jp/fjava/special/jna/jna_1.html
分享到:
2014-11-10 12:09
浏览 6866
评论