首次在Java8中,使用jni调用C的dll

本文详细介绍了如何在Java8中使用JNI调用C语言生成的DLL,包括创建Java接口、实现、编译DLL、设置路径以及处理常见问题,如类文件查找和JNI头文件路径设置。同时提及了JNA作为另一种解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这次是使用C语言生成的dll

以下是在Java 8中使用JNI调用DLL的步骤清单:

  1. 编写Java类接口:创建一个Java接口,定义与本地方法对应的方法签名。
public interface MyNativeInterface {
    void nativeMethod();
}
  1. 编写Java类实现:创建一个Java类实现这个接口,用于加载本地库并声明本地方法。
public class MyNativeImplementation implements MyNativeInterface {
    static {
        System.loadLibrary("myNativeLibrary");
    }
    
    public native void nativeMethod();
}
  1. 生成头文件:使用Java本地接口工具(javah)生成头文件。
javah -jni com.example.MyNativeImplementation
  1. 实现本地方法:使用C/C++编写本地方法的实现,并编译成动态链接库。
#include <jni.h>
#include "com_example_MyNativeImplementation.h"

JNIEXPORT void JNICALL Java_com_example_MyNativeImplementation_nativeMethod(JNIEnv *env, jobject obj) {
    // 实现本地方法
}
  1. 编译动态链接库:使用合适的编译器(如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"
  1. 设置路径:将生成的DLL文件放置在Java库加载路径中。

  2. 调用本地方法:在Java代码中调用本地方法。

public class Main {
    public static void main(String[] args) {
        MyNativeInterface nativeInterface = new MyNativeImplementation();
        nativeInterface.nativeMethod();
    }
}
  1. 运行程序:运行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语言学习踩坑记这篇文章,文中有提到案例代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值