| |
有各种各样的原因需要使用到已有的遗留代码。此时,使用jni,可以非常方便地调用已有的稳定的本地代码。把遗留系统和新的代码整合起来。下面我们来看如何写一个本地c代码调用的hello world版本。
在本实例中,包括下面几个类: hellonative.java:实用类,提供一个静态本地方法greeting(),打印出一个消息串。其中greeting方法调用了下面的本地代码。 hellonative.c:本地实现代码。 hellonativetest.java:应用主文件,调用hellonative实用类的greeting()方法。 hellonative.java
//hellonative.javaclass hellonative{ public native static void greeting(); static { //hellonative是下面将由hellonative.c生成的dll文件。system.loadlibrary("hellonative"); }};
编译上面的.java文件后,在生成的.class目录下,使用javah命令生成hellonative.class的c头文件: javah hellonative hellonative.h
生成的hellonative.h文件如下:
/* do not edit this file - it is machine generated */#include <jni.h>/* header for class hellonative */#ifndef _included_hellonative#define _included_hellonative#ifdef __cplusplusextern "c" {#endif/* * class: hellonative * method: greeting * signature: ()v */jniexport void jnicall java_hellonative_greeting (jnienv *, jclass);#ifdef __cplusplus}#endif#endif hellonative.c 拷贝生成的hellonative.h,另存为hellonative.c,并填充jnicall java_hellonative_greeting方法体,得到下面的 hellonative.c:/* do not edit this file - it is machine generated */#include <jni.h>/* header for class hellonative */#ifndef _included_hellonative#define _included_hellonative#ifdef __cplusplusextern "c" {#endif/* * class: hellonative * method: greeting * signature: ()v */jniexport void jnicall java_hellonative_greeting (jnienv * env, jclass cl){ printf("hello, native world!");}#ifdef __cplusplus }#endif#endif 使用windows自带的c/c++编译器,编译上面的hellonative.c:
cl -id:j2sdk1.4.1include -id:j2sdk1.4.1includewin32 -ld hellonative.c -fehellonative.dll
执行这条命令后将生成hellonative.dll文件。这个dll动态链接库就是下面我们在hellonative.java文件中调用的本地文件。如果是在unix/linux下,请使用相应操作系统的c编译器,生成的库文件是hellonative.so。 开始运行吧
至此,我们编写的windows平台上的本地库文件和java文件已经准备就绪,下面写一个简单的测试程序来测试一下本地调用吧。
class hellonativetest { public static void main(string[] args) { hellonative.greeting(); }} 编译、运行这个程序,将打印出native版的: hello, native world!
也许你认为这并没有什么特别,但如果你知道这个消息串是使用你自己写的c库文件中调用生成的时候,你就会有知道这有着非常重大的意义。就好像寻宝者在人迹罕至的荒山之中,突然看到一块史前陶片,陶片本身并没有什么特别,但这,也许已经为你启开了宝藏之门。
from-javaresearch
|
|