常州网站制作,公司app开发收费价目表,网站上怎么做动图,低代码开发平台 开源这次是使用C语言生成的dll
以下是在Java 8中使用JNI调用DLL的步骤清单#xff1a;
编写Java类接口#xff1a;创建一个Java接口#xff0c;定义与本地方法对应的方法签名。
public interface MyNativeInterface {void nativeMethod();
}编写Java类实现#xff1a;创建一…这次是使用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.hJNIEXPORT 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设置路径将生成的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 -ID:\Program\Java\jdk-1.8\include -ID:\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.hJNIEXPORT void JNICALL Java_org_ming_jni_MyNativeImplementation_nativeMethod(JNIEnv *env, jobject obj) {// 实现本地方法printf(Hello, World C Fan! \n);
}Java代码无变化。
还有一种方法是使用JNAJNA的案例请查看Go语言学习踩坑记这篇文章文中有提到案例代码