JNI 之 hello world

  JNI是 Java Native Interface的缩写,它的设计目的是:
  
  The standard Java class library may not support the platform-dependent features needed by your application.
  
  You may already have a library or application written in another programming language and you wish to make it accessible to Java applications
  
  You may want to implement a small portion of time-critical code in a lower-level programming language, such as assembly, and then have your Java application call these functions
 
 
JNI的步骤:
1.编写一个带有 native 的方法,注意这个方法和接口中的方法一样,是没有实现的,同时导入动态库文件。
2.用javac 编译这个类
3.用javah -jni java类名   生成扩展名为h的头文件
4.用c或c++实现本地方法,再这之间首先要导入xx.h头文件
5.将c或c++编写的文件生成动态链接库
 
编写的java文件如下:
 public class Test {
 static {
  System.loadLibrary("test"); 
 }

 public native void test();
 
 public static void main(String[] args) {
  Test t = new Test();
  t.test(); 
 }
}
 
 
 
javah生成的头文件如下:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class Test */
#ifndef _Included_Test
#define _Included_Test
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     Test
 * Method:    test
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_Test_test
  (JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
 

 
最后是Test.c文件:
#include <jni.h>
#include "Test.h"
#include <stdio.h>
JNIEXPORT void JNICALL Java_Test_test(JNIEnv *env,jobject obj) {
 printf("Hello world!/n");
 return; 
}

 
通过VC++的cl命令,生成Test.dll文件。
cl -I%java_home%/include -I%java_home%/include/win32 -LD Test.c -FeTest.dll
这里补充一下,System.loadLibrary("xx"); 这里不需要加.dll后缀,而且它不区分大小写。
 
最后运行 java Test
得到的结果就是:
Hello world!
而这一切不是在java中完成的,是java调用本地文件所得到的。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值