Java中运行并且自定义本地方法 #native

本文详细介绍了如何在Java中使用本地方法,通过示例展示了如何定义、生成和实现native方法,以及如何将C/C++编译成.dll文件并加载到Java虚拟机中。整个过程包括使用javah生成头文件,编写C/C++代码,编译生成.dll,最后在Java代码中调用本地方法。
摘要由CSDN通过智能技术生成

如何在Java中运用并且自定义本地方法?

可以使用本地C/C++的类库,如何使用:

  1. 定义本地方法native方法
    public class Example {
        static {
            System.load("E:/project_java/OO(Object-Orientde)/IDEAproject/JVMDemo/chapter4/resources/example.dll");
        }
        public native static void hello();
    }

     

  2. 创建 .dll文件:
  3. 使用 javah -jni [全类名] 生成.h头文件。 如:javah -jni com.self.java.Example 生成 com_self_java_Example.h,并且导入 JAVA_HOME\include\jni.h 和 JAVA_HOME\include\win32\jni_md.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

     

  4. 在.c文件中实现 .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;
    };
    
    

     

  5.  在.c文件目录下使用
    gcc com_self_java_Example.c com_self_java_Example.h jni.h -fPIC -shared -o example.dll

     生成.dll 文件,使用gcc命令需要安装mingw64/32

  6. 在java的Example类中使用System.load()方法加载 .dll 文件,即可在虚拟机的本地方法区中加载该本地方法。

  7. 编写主类
    public class NativeMethodTest {
        public static void main(String[] args) {
            String hello = Example.hello();
            System.out.println(hello);
        }
    }
     
  8. 点击运行主类 输出结果为 hello word!C
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值