Java中运行并且自定义本地方法 #native
2021/5/30 20:50:08
本文主要是介绍Java中运行并且自定义本地方法 #native,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
如何在Java中运用并且自定义本地方法?
可以使用本地C/C++的类库,如何使用:
- 定义本地方法native方法
public class Example { static { System.load("E:/project_java/OO(Object-Orientde)/IDEAproject/JVMDemo/chapter4/resources/example.dll"); } public native static void hello(); }
- 创建 .dll文件:
- 使用 javah -jni [全类名] 生成.h头文件。 如:javah -jni com.self.java.Example 生成 com_self_java_Example.h
/* DO NOT EDIT THIS FILE - it is machine generated */ #include "jni.h" /* Header for class com_self_java_Example */ #ifndef _Included_com_self_java_Example #define _Included_com_self_java_Example #ifdef __cplusplus extern "C" { #endif /* * Class: com_self_java_Example * Method: hello * Signature: ()Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_com_self_java_Example_hello (JNIEnv *, jclass); #ifdef __cplusplus } #endif #endif
- 实现 .h文件中的方法
#include "jni.h" #include "com_self_java_Example.h" JNIEXPORT jstring JNICALL Java_com_self_java_Example_hello (JNIEnv * env, jclass obj){ jstring str = (jstring) "hello word!C"; printf("hello word!C"); return str; };
并且导入 JAVA_HOME\include\jni.h 和 JAVA_HOME\include\win32\jni_md.h
- 在.c文件目录下使用
gcc com_self_java_Example.c com_self_java_Example.h jni.h -fPIC -shared -o example.dll
生成.dll 文件,使用gcc命令需要安装mingw64/32
-
在java的Example类中使用System.load()方法加载 .dll 文件,即可在虚拟机的本地方法区中加载该本地方法。
- 点击运行 输出结果为 hello word!C
这篇关于Java中运行并且自定义本地方法 #native的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-07-02springboot项目无法注册到nacos-icode9专业技术文章分享
- 2024-06-26结对编程到底难不难?答案在这里
- 2024-06-19《2023版Java工程师》课程升级公告
- 2024-06-15matplotlib作图不显示3D图,怎么办?
- 2024-06-1503-Loki 日志监控
- 2024-06-1504-让LLM理解知识 -Prompt
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现
- 2024-06-03为什么以及如何要进行架构设计权衡?
- 2024-05-31全网首发第二弹!软考2024年5月《软件设计师》真题+解析+答案!(11-20题)