JAVA Jni的使用
1.1在java项目中生成.h头文件
关键代码
static
{
try{
//lab2就是要加载的dll的名字,这是相对路径加载方式
System.loadLibrary("Dll1");
}
catch(UnsatisfiedLinkError e){
System.err.println( "Cannot load J2C library:\n"+e.toString() );
}
}
// source path and target path for two files
public native boolean compress(String src_path,String target_path);
public native boolean Decompress(String src_path,String target_path);
使用命令生成xxx.Class
javac path\xxx.java
根据xxx.Class使用javah生成.h头文件给c++用
javah -classpath . -jni com.xx.xx //当前路径和包名
1.2在VS2019中生成DLL给JAVA用
将上一步生成的xxx.h文件放入项目头文件中,然后需要到java文件中找到jawt.h等四个文件,可以放入本地也可以include引用。在vs的dll项目中用lab2.cpp对xxx.h文件进行实现。项目截图:
一些注意事项以及bug:
1-要在release的版本生成解决方案。
2-有一个预编译头设置成不使用
1.3 JAVA调用dll,使用c++编写的函数
直接附代码 JAVA JNI demo 以及 C++压缩解压缩代码
public class lab2 {
static
{
try{
//lab2就是要加载的dll的名字,这是相对路径加载方式
System.loadLibrary("Dll1");
}
catch(UnsatisfiedLinkError e){
System.err.println( "Cannot load J2C library:\n"+e.toString() );
}
}
// source path and target path for two files
public native boolean compress(String src_path,String target_path);
public native boolean Decompress(String src_path,String target_path);
public static void main(String args[])
{
lab2 test = new lab2();
String a = "D:\\test.txt";
String b = "D:\\compress.txt";
String c = "D:\\uncompress.txt";
// compress a into b
boolean judge_compress = test.compress(a, b);
// compress a into b and decompress b into c
boolean judge_decompress = test.Decompress(a, c);
}
}
JNIEXPORT jboolean JNICALL Java_com_yh_lab2_compress
(JNIEnv* env, jobject, jstring src, jstring target) {
try {
const char* src_path = (env)->GetStringUTFChars(src, JNI_FALSE);
const char* target_path = (env)->GetStringUTFChars(target, JNI_FALSE);
FILE* File_src = fopen(src_path, "r");
FILE* File_compress = fopen(target_path, "w");
unsigned long len_src;
unsigned long len_compress;
unsigned char* buffer_src = new unsigned char[MaxBufferSize];
unsigned char* buffer_compress = new unsigned char[MaxBufferSize];
// 压缩文件:
len_src = fread(buffer_src, sizeof(char), MaxBufferSize - 1, File_src);
compress(buffer_compress, &len_compress, buffer_src, len_src);
fwrite(buffer_compress, sizeof(char), len_compress, File_compress);
fclose(File_src);
fclose(File_compress);
cout << "compress succeed!" << endl;
return true;
}
catch (const char* msg) {
cout << "falure!" << endl;
return false;
}
}
1.4 文件说明
Dll1.zip 为vs创建的dll项目,可以编译出Dll1供java调用,里面有实现压缩与解压缩的代码。
lab2.zip是JAVA调用C++函数的jni框架demo