package com.zzw.demo1; public class Hello { static { System.loadLibrary("hello"); } private native String say(String str); private native float average(int[] a); private native int max(int[][] f); public static void main(String[] args) { Hello hello = new Hello(); int[][] a = {{1,2,3,5},{4,100,5,6}}; System.out.println(hello.max(a)); } }
这次,文件在包中,并且传入二维数组时的处理方法。
首先,进入java源码的路径,并且编译它
然后,将得到的头文件加入VS,并且编写C代码
#include<stdio.h> #include "jni.h" #include "com_zzw_demo1_Hello.h" JNIEXPORT jstring JNICALL Java_com_zzw_demo1_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_com_zzw_demo1_Hello_average (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; } JNIEXPORT jint JNICALL Java_com_zzw_demo1_Hello_max (JNIEnv *env, jobject object, jobjectArray array) { int i, j; jint max; //获取数组行数 int size1 = (*env)->GetArrayLength(env, array); printf("数组行数为:%d\n", size1); jarray myarray = (*env)->GetObjectArrayElement(env, array, 0); //获取数组列数 int size2 = (*env)->GetArrayLength(env, myarray); printf("数组列数为:%d\n", size2); for (i = 0;i < size1;i++) { myarray = (*env)->GetObjectArrayElement(env, array, i); jint *element = (*env)->GetIntArrayElements(env, (jintArray)myarray, NULL); for (j = 0;j < size2;j++) { if (j == 0) max = element[0]; if (max < element[j]) max = element[j]; } } return max; }
最后,将该dll文件加入到eclipse中,并且在buildPath中注意添加dll的路径。
最后,运行即可得到结果
时间: 2024-10-18 09:20:17