静态注册实现
- 首先在JAVA中声明一个本地方法:
public class Register {
public native String HelloWorld();
}
- 编译java文件:在终端中执行以下命令:
javac Register.java
将会生成一个Register.class的字节码文件
![](https://i-blog.csdnimg.cn/blog_migrate/8873b56876ecd1bbe1f7b98c19a21f24.png)
- 编译头文件:
javah Register
// 将会生成一个Register.h的头文件
![](https://i-blog.csdnimg.cn/blog_migrate/5b9658acdef4dddecf4d75637f1eb40e.png)
-
为了方便,我们将头文件放到一个C环境的IDE中
这样会报错,是因为我们需要引入两个头文件,jdk的安装目录下找到include/jni.h和 include/win32/jni_md.h文件,放到我们的c项目中 -
创建一个同名的c文件(当然这里不是必须要同名的,这是一种规范),引入头文件,实现头文件中的Java_Register_HelloWorld方法
-
在CMakeLists中引入库:
其中第一个参数是库名称,可自定义;
第二个参数是SHARED代表共享库;
第三个参数和第四各个参数分别是我们的c文件和头文件; -
build一下项目,会在cmake-build-debug目录中生成我们想要的依赖库文件:
-
在java中引入这个库:
科普一下哈:
system.load()/system.loadLibrary() 区别
System.load
System.load 参数必须为库文件的绝对路径,可以是任意路径,例如: System.load("C:\Documents and Settings\TestJNI.dll"); //Windows
System.load("/usr/lib/TestJNI.so"); //Linux
System.loadLibrary
System.loadLibrary 参数为库文件名,不包含库文件的扩展名。
System.loadLibrary ("TestJNI"); //加载Windows下的TestJNI.dll本地库
System.loadLibrary ("TestJNI"); //加载Linux下的libTestJNI.so本地库
- 在main函数中调用本地方法,就可以执行了,看下打印结果: