这次是使用C语言生成的dll
以下是在Java 8中使用JNI调用DLL的步骤清单:
- 编写Java类接口:创建一个Java接口,定义与本地方法对应的方法签名。
public interface MyNativeInterface {
void nativeMethod();
}
- 编写Java类实现:创建一个Java类实现这个接口,用于加载本地库并声明本地方法。
public class MyNativeImplementation implements MyNativeInterface {
static {
System.loadLibrary("myNativeLibrary");
}
public native void nativeMethod();
}
- 生成头文件:使用Java本地接口工具(javah)生成头文件。
javah -jni com.example.MyNativeImplementation
- 实现本地方法:使用C/C++编写本地方法的实现,并编译成动态链接库。
#include <jni.h>
#include "com_example_MyNativeImplementation.h"
JNIEXPORT void JNICALL Java_com_example_MyNativeImplementation_nativeMethod(JNIEnv *env, jobject obj) {
// 实现本地方法
}
- 编译动态链接库:使用合适的编译器(如gcc)编译动态链接库。
gcc -shared -o myNativeLibrary.dll com_example_MyNativeImplementation.c -I"%JAVA_HOME%\include" -I"%JAVA_HOME%\include\win32"
gcc -shared -o scanDir.dll jni.c utils.c -I "D:\Program\Java\jdk-1.8\include" -I "D:\Program\Java\jdk-1.8\include\win32"
-
设置路径:将生成的DLL文件放置在Java库加载路径中。
-
调用本地方法:在Java代码中调用本地方法。
public class Main {
public static void main(String[] args) {
MyNativeInterface nativeInterface = new MyNativeImplementation();
nativeInterface.nativeMethod();
}
}
- 运行程序:运行Java程序,触发对本地方法的调用。
这些步骤会帮助您使用JNI在Java中调用DLL。确保在实际开发中按照安全和最佳实践进行操作,并适当处理异常情况。
其中,
第三步中,
使用到的命令,总是报错“错误: 找不到 ‘MyNativeImplementation’ 的类文件。”。
最后是使用下面的命令成功的。
javah -classpath D:\workspace\java_workspace\TestHttp\target\classes org.ming.jni.MyNativeImplementation
第五步中,使用相对路径JAVA_HOME无法找到jni.h文件。后来是使用的是绝对路径
gcc -shared -o myNativeLibrary.dll myNativeLibrary.c -I"D:\Program\Java\jdk-1.8\include" -I"D:\Program\Java\jdk-1.8\include\win32"
我将代码贴出。
生成的jni头文件
org_ming_jni_MyNativeImplementation.h
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class org_ming_jni_MyNativeImplementation */
#ifndef _Included_org_ming_jni_MyNativeImplementation
#define _Included_org_ming_jni_MyNativeImplementation
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: org_ming_jni_MyNativeImplementation
* Method: nativeMethod
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_org_ming_jni_MyNativeImplementation_nativeMethod
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
我写的C语言的实现文件
#include <jni.h>
#include "org_ming_jni_MyNativeImplementation.h"
JNIEXPORT void JNICALL Java_org_ming_jni_MyNativeImplementation_nativeMethod(JNIEnv *env, jobject obj) {
// 实现本地方法
printf("Hello, World C Fan! \n");
}
Java代码无变化。
还有一种方法是使用JNA,JNA的案例请查看Go语言学习踩坑记这篇文章,文中有提到案例代码