1 public class testdll{ 2 static{ 3 System.loadLibrary("dllname");//不包含[.dll] 4 } 5 6 public native void sayHello(); 7 8 public static void main(String[] args){ 9 testdll test = new testdll();10 test.sayHello();11 }12 }
2.生成头文件 testdll.h
javah testdll testdll.h文件内容如下:1 /* DO NOT EDIT THIS FILE - it is machine generated */ 2 #include <jni.h> 3 /* Header for class testdll */ 4 5 #ifndef _Included_testdll 6 #define _Included_testdll 7 #ifdef __cplusplus 8 9 extern "C" {10 #endif11 /*12 * Class: testdll13 * Method: sayHello14 * Signature: ()I15 */16 17 JNIEXPORT void JNICALL Java_testdll_sayHello(JNIEnv *, jobject);18 #ifdef __cplusplus19 }20 #endif21 #endif
函数名有特定格式,不能随意修改,Java_class_method,而且只能由class类对象才能调用,因为JNI是通过类名来查找对应方法的。
3.生成动态库 使用VS新建一个空的dll工程,将生成的头文件导入工程。新建.c或者.cpp,实现头文件中的函数:1 #include <stdlib.h>2 3 JNIEXPORT void JNICALL Java_testdll_sayHello4 (JNIEnv *env, jobject obj){5 PRintf("hello world/n");6 }
4.编译生成dll文件
将jni.h、jni_md.h文件复制到VS环境的include目录下 jni.h------------------jdk安装目录/include jni_md.h-------------jdk安装目录/include/win32 编译生成testdll.dll5.执行 将编译好的.dll文件放到path环境变量的目录下,或者放到eclipse工程的跟目录下,然后执行Java程序即可。 也可以通过以下参数指定dll文件的目录 java -Djava.library.path=dll文件的目录新闻热点
疑难解答