作用:使Java能够同C/C++动态库(dll)进行交互。
编写过程:
1、native接口类,其中方法用native修饰,没有方法体。
2、通过javah命令编译native接口类,会生成.h的头文件。
3、用C编写一个dll文件
(1)需要引入刚生成的.h头文件
(2)实现头文件中的方法(会对应到native接口类中的方法)。
(3)方法中正常调用dll文件即可。
4、特殊变量的参数和返回值,使用方式可以参看jni.h中的java类型与c类型转换的相关方法。
代码例子:
native接口类:
1 public class DLLSchema { 2 /* 参数和返回值可以根据需要 */ 3 public native int test (int param); 4 }
程序调用方式:
1 public class DLLCall { 2 static { 3 /* 加载DLL文件,不用加后缀名 */ 4 System.loadLibrary("dll"); 5 } 6 7 public void call() { 8 DLLSchema dll = new DLLSchema(); 9 int result_int = dll.test(100); 10 } 11 }
javah:
命令:javah test.DLLSchema
编译后会生成一个 test_DLLSchema.h 的文件:
C部分调用:
1 #include <stdio.h> 2 #include <Windows.h> 3 4 #include "com_loong_demo_jni_DLLSchema.h" 5 6 // 加载指定dll 7 HINSTANCE Hint = ::LoadLibrary("dll.dll"); 8 9 // 实现方法体 10 JNIEXPORT jint JNICALL Java_test_DLLSchema_test(JNIEnv *, jobject, jint param) { 11 // 新建函数类型 12 typedef int (*TEST)(int param_); 13 // 获取调用函数 14 TEST _test = (TEST)GetProcAddress(Hint,"TEST"); 15 // 调用函数 16 int result = _test(param); 17 return result; 18 }