java调用native方法。
环境:
jdk:11
idea:2024
visual studio:2019
c++:14
步骤
- 使用IDEA创建java工程
- 创建NativeCppMethod类
public class NativeCppMethod {
public native int sayHello();
public native int plus(int a, int b);
public native int minus(int a, int b);
public native int min(int... nums);
}
- 使用javac -h 生成对应的c++头文件
生成的NativeCppMethod.h
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class NativeCppMethod */
#ifndef _Included_NativeCppMethod
#define _Included_NativeCppMethod
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: NativeCppMethod
* Method: sayHello
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_NativeCppMethod_sayHello
(JNIEnv *, jobject);
/*
* Class: NativeCppMethod
* Method: plus
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_NativeCppMethod_plus
(JNIEnv *, jobject, jint, jint);
/*
* Class: NativeCppMethod
* Method: minus
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_NativeCppMethod_minus
(JNIEnv *, jobject, jint, jint);
/*
* Class: NativeCppMethod
* Method: min
* Signature: ([I)I
*/
JNIEXPORT jint JNICALL Java_NativeCppMethod_min
(JNIEnv *, jobject, jintArray);
#ifdef __cplusplus
}
#endif
#endif
- 使用VisualStudio创建C++动态库
- 将jdk里的jni.h和jni_md.h头文件,第三步生成的头文件(需要将引入<jni.h>改为"jni.h")拷贝到项目里,创建NativeCppMethod.cpp文件
- 完成NativeCppMethod.cpp逻辑
#include "NativeCppMethod.h"
#include "jni.h"
#include <iostream>
using namespace std;
JNIEXPORT jint JNICALL Java_NativeCppMethod_sayHello(JNIEnv* env, jobject obj)
{
cout << "hello world!" << endl;
return 0;
}
JNIEXPORT jint JNICALL Java_NativeCppMethod_plus(JNIEnv* env, jobject obj, jint a, jint b)
{
return a + b;
}
JNIEXPORT jint JNICALL Java_NativeCppMethod_minus(JNIEnv* env, jobject obj, jint a, jint b)
{
return a - b;
}
JNIEXPORT jint JNICALL Java_NativeCppMethod_min(JNIEnv* env, jobject obj, jintArray arr)
{
jint* jintPtr = env->GetIntArrayElements(arr, NULL);
jsize len = env->GetArrayLength(arr);
if (len <= 0) {
return -1;
}
jint min = jintPtr[0];
for (jint i = 1; i < len; ++i) {
if (jintPtr[1] < min) {
min = jintPtr[i];
}
}
return min;
}
- 编译生成64位release版本动态dll,将dll拷贝到java项目里
- 编写main函数
public class Main {
static {
System.loadLibrary("DllForJavaTest2");
}
public static void main(String[] args) {
NativeCppMethod nativeCppMethod = new NativeCppMethod();
int a = 10, b = 4, c[] = {1, 2, 3, 6, 7, 4};
nativeCppMethod.sayHello();
System.out.println("plus:" + nativeCppMethod.plus(a, b));
System.out.println("minus:" + nativeCppMethod.minus(a, b));
System.out.println("min:" + nativeCppMethod.min());
System.out.println("min:" + nativeCppMethod.min(a));
System.out.println("min:" + nativeCppMethod.min(a, b));
System.out.println("min:" + nativeCppMethod.min(c));
}
}
- 运行
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。