在Java中使用native方法调用c++代码
1、写Java代码Hello.java
public class Hello {
public native void helloFromCPP();
}
2、编译java文件
输入cmd进入命令行窗口,输入以下命令进行编译
javac Hello.java -h .
得到的Hello.h代码如下:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class Hello */
#ifndef _Included_Hello
#define _Included_Hello
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: Hello
* Method: helloFromCPP
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_Hello_helloFromCPP
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
3、根据头文件写cpp文件
注:这里的cpp文件的内容,首先是把前面h文件里的ifndef、endif、define以及注释删掉,然后再编写自己的函数代码。
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class Hello */
#include <stdio.h>
#include "Hello.h"
JNIEXPORT void JNICALL Java_Hello_helloFromCPP
(JNIEnv *, jobject){
printf("Hello from C++!\n");
}
4、安装c/c++的编译器
此处不演示。
5、编译生成hello.dll文件
找到jdk文件夹下的include文件夹下的jni.h,这里我的路径为D:\Java1.8\include
然后点进win32文件夹,发现jni_md.h文件就在这里,记住这个路径,这里我的路径是D:\Java1.8\include\win32
然后就是编译生成hello.dll,命令行代码为:
gcc -I "D:\Java1.8\include" -I "D:\Java1.8\include\win32" -shared -o hello.dll Hello.cpp
6、编写测试代码
在Hello.java中加入载入hello.dll文件的代码
public class Hello {
public native void helloFromCPP();
static {
System.load("D:/Code/java/java_and_c/src/main/java/hello.dll");
}
}
编写测试代码
public class Test {
public static void main(String[] args) {
Hello hello = new Hello();
hello.helloFromCPP();
}
}
如果需要使用c中的带参数的函数呢?试试!
1、创建类,定义native方法
public class Hello_with_params {
public native void helloFromCPPWithParam(int a, String b);
}
2、编译Java文件
输入cmd进入命令行窗口,输入以下命令进行编译
javac Hello_with_params.java -h .
3、写cpp文件
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class Hello_with_params */
#include<stdio.h>
#include <string>
#include "Hello_with_params.h"
void printString(const jchar* str) {
// 使用循环和指针算术遍历字符数组
while (*str != '\0') {
printf("%c", *str);
str++;
}
printf("\n");
}
JNIEXPORT void JNICALL Java_Hello_1with_1params_helloFromCPPWithParam
(JNIEnv *env, jobject, jint a, jstring jstr){
printf("Hello from C++\n");
printf("a = %d\n", a);
/*需要对字符串b做一些处理,否则无法正常显示。*/
const jchar* str = (env)->GetStringChars(jstr, NULL);
printf("你好啊\n");
printf("b =");
printString(str);
}
4、编译生成dll文件
gcc -I "D:\Java1.8\include" -I "D:\Java1.8\include\win32" -shared -o Hello_with_params.dll Hello_with_params.cpp
5、编写测试代码
在Hello.java中加入载入hello.dll文件的代码
public class Hello_with_params {
public native void helloFromCPPWithParam(int a, String b);
static {
System.load("D:/Code/java/java_and_c/src/main/java/Hello_with_params.dll");
}
}
编写测试代码,然后运行。
public class Test {
public static void main(String[] args) {
Hello_with_params hello = new Hello_with_params();
hello.helloFromCPPWithParam(123, "This is Striverzb calling from Java");
}
}