首先写好Java代码
public class Hello { static { System.loadLibrary("hello"); } private native String say(String str); private native float average(int[] a); public static void main(String[] args) { Hello hello = new Hello(); String str = hello.say("I am zzw,nice to meet you JNI"); System.out.println(str); int[] a = {1,2,3,4,5}; System.out.println(hello.average(a)); } }
然后在命令行下编译它,javac Hello.java,并且得到其对应的C语言头文件,javah Hello,即可得到头文件如下
/* 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: say * Signature: (Ljava/lang/String;)Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_Hello_say (JNIEnv *, jobject, jstring); /* * Class: Hello * Method: average * Signature: ([I)F */ JNIEXPORT jfloat JNICALL Java_Hello_average___3I (JNIEnv *, jobject, jintArray); #ifdef __cplusplus } #endif #endif
然后打开VS,写入C代码,同时添加jni.h和jni_md.h两个头文件,
#include<stdio.h> #include "jni.h" #include "Hello.h" JNIEXPORT jstring JNICALL Java_Hello_say (JNIEnv *env, jobject object, jstring str) { const char *cstr = (*env)->GetStringUTFChars(env, str, NULL); if (NULL == cstr) return NULL; printf("this is C,I received: %s\n", cstr); (*env)->ReleaseStringUTFChars(env, str, cstr); char input[128]; printf("请输入一个字符串:"); scanf("%s", input); return (*env)->NewStringUTF(env, input); } JNIEXPORT jfloat JNICALL Java_Hello_average___3I (JNIEnv *env, jobject object, jintArray array) { jint *carray = (*env)->GetIntArrayElements(env, array, NULL); if (NULL == carray) return 0; jsize length = (*env)->GetArrayLength(env, array); jfloat aver = 0; jint sum = 0; int i; for (i = 0;i < length;i++) { sum += carray[i]; } aver = (jfloat)sum / length; return aver; }
最后,点击编译生成dll文件,加到java文件夹中,运行java Hello,即可成功运行。
时间: 2024-11-03 02:53:29