JNI(Java Native Interface)
Java调用C/C++,C/C++调用Java的一套API
前言:
学习JNI需要C/C++的相关知识,而且需要研究JNI手册.
想学习的同学,请follow我的学习笔记NDK开发学习笔记
1:在eclipse中编写native方法
public class Java2cpp {
static {
System.loadLibrary("Project4");
}
public native int DLL_ADD(int a,int b);//加
public native int DLL_SUB(int a,int b);//减
public native int DLL_MUL(int a,int b);//乘
public native int DLL_DIV(int a,int b);//除
public static void main(String args[]){
int sum = 0;
Java2cpp test = new Java2cpp();
sum = test.DLL_ADD(2, 4);
System.out.println("Java call cpp dll result:" + sum);
}
}
}
2.javah命令,生成.h头文件
第一步:javac Java2cpp.java 生成java2cpp.class
-
第二步:javah Java2cpp 生成Java2cpp.h头文件,内容如下:
//生成的C++头文件Java2cpp.h
/* DO NOT EDIT THIS FILE - it is machine generated */
#include "jni.h"
/* Header for class Java2cpp */
#ifndef _Included_Java2cpp
#define _Included_Java2cpp
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: Java2cpp
* Method: DLL_ADD
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_Java2cpp_DLL_1ADD
(JNIEnv *, jobject, jint, jint);
/*
* Class: Java2cpp
* Method: DLL_SUB
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_Java2cpp_DLL_1SUB
(JNIEnv *, jobject, jint, jint);
/*
* Class: Java2cpp
* Method: DLL_MUL
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_Java2cpp_DLL_1MUL
(JNIEnv *, jobject, jint, jint);
/*
* Class: Java2cpp
* Method: DLL_DIV
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_Java2cpp_DLL_1DIV
(JNIEnv *, jobject, jint, jint);
#ifdef __cplusplus
}
#endif
#endif
3.复制.h头文件,jni.h和jni_md.h到CPP工程中
-
用visual studio新建空C++项目,引入头文件Java2cpp.h,这边因为没有jni.h和jni_md.h,我们也要导入(jni.h和jni_md.h在jdk的lib中),
4.实现.h头文件中声明的函数
编写头文件Java2cpp.h的实现即testdll.cpp.部分代码如下.
#include "Java2cpp.h"
/*
* Class: Java2cpp
* Method: DLL_ADD
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_Java2cpp_DLL_1ADD
(JNIEnv *env, jobject obj, jint a, jint b){
int var = 0;
var = a + b;
return var;
}
/*
* Class: Java2cpp
* Method: DLL_SUB
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_Java2cpp_DLL_1SUB
(JNIEnv *env, jobject obj, jint a, jint b){
int var = 0;
var = a-b;
return var;
}
5.生成dll文件
-
配置文件,右键上3图项目结构选择属性
生成解决方案即可
6.配置dll文件所在目录到环境变量
将dll文件所在目录配置到Path中,例如我把dll放在 D:\DllTools ,
则需要将 D:\DllTools; 添加到path的最前面.
7.重启Eclipse
重启查看结果
public class Java2cpp {
static {
System.loadLibrary("Project4");
}
public native int DLL_ADD(int a,int b);//加
public native int DLL_SUB(int a,int b);//减
public native int DLL_MUL(int a,int b);//乘
public native int DLL_DIV(int a,int b);//除
public static void main(String args[]){
int sum = 0;
Java2cpp test = new Java2cpp();
sum = test.DLL_ADD(2, 4);
System.out.println("Java call cpp dll result:" + sum);
}
}
//console 显示的结果
Java call cpp dll result:6