1.在Java中先编写好native方法,以便实现对dll的调用,可使用Eclipse(自动编译,省去手动),例子如下
package com.xiganglive.dll;
public class Native {
static native int add(int a,int b);
static {
System.loadLibrary("nativedll");
}
}
2.进入eclipse的编译输出根目录,默认为bin/,使用javah命令.h生成头文件
$ javah --help
Usage:
javah [options] <classes>
where [options] include:
-o <file> Output file (only one of -d or -o may be used)
-d <dir> Output directory
-v -verbose Enable verbose output
-h --help -? Print this message
-version Print version information
-jni Generate JNI-style header file (default)
-force Always write output files
-classpath <path> Path from which to load classes
-cp <path> Path from which to load classes
-bootclasspath <path> Path from which to load bootstrap classes
<classes> are specified with their fully qualified names
(for example, java.lang.Object).
#如果你的Java程序带有package,需要设置classpath
$ javah -classpath . -jni com.xiganglive.dll.Native
# bin目录中将会生成对应的.h文件,此例中为com_xiganglive_dll_Native.h
$ ls
com/ com_xiganglive_dll_Native.h
3.创建c++项目,设置为dll模板
snipaste20200415_213708.pngsnipaste20200415_214307.png将com_xiganglive_dll_Native.h复制到C++项目目录里
在C++项目里导入h文件
导入后会发现找不到<jni.h>,需配置项目属性include目录,添加Java根目录下的include目录
snipaste20200415_215050.png
snipaste20200415_215011.png
4.现在就可以执行build,得到对应dll,放入java中引用
snipaste20200415_215412.png5.The last,如果出现错误,请按如下步骤检查你的操作
a.检查你javah对应Java版本是否与实际运行一致
b.检查C++项目的项目属性是否正确引入include目录
c.build出来的dll,需与编译时保持一致,x86编译出的dll只能在32位JVM上运行,反之亦然
网友评论