长沙网站改版,wordpress 伪静态 seo,高级又小众的公众号,天长网站制作在上一期讲了基本类型的基本使用#xff0c;这期来说一说数组的基本使用
HelloJNI.java#xff1a;实现myArray函数#xff0c;把一个整型数组转换为双精度型数组
public class HelloJNI { static {System.loadLibrary(hello); }private native String HelloW…在上一期讲了基本类型的基本使用这期来说一说数组的基本使用
HelloJNI.java实现myArray函数把一个整型数组转换为双精度型数组
public class HelloJNI { static {System.loadLibrary(hello); }private native String HelloWorld();private native double avg(int n1, int n2);private static native double[] myArray(int[] arr);public static void main(String[] args) {System.out.println(new HelloJNI().HelloWorld());System.out.println(new HelloJNI().avg(8,3));int[] arr{6,4,3,2,11};double[] ansmyArray(arr);for (double i : ans) {System.out.println(i*2);}}}生成HelloJNI.h
/* DO NOT EDIT THIS FILE - it is machine generated */
#include jni.h
/* Header for class HelloJNI */#ifndef _Included_HelloJNI
#define _Included_HelloJNI
#ifdef __cplusplus
extern C {
#endif
/** Class: HelloJNI* Method: HelloWorld* Signature: ()Ljava/lang/String;*/
JNIEXPORT jstring JNICALL Java_HelloJNI_HelloWorld(JNIEnv *, jobject);/** Class: HelloJNI* Method: avg* Signature: (II)D*/
JNIEXPORT jdouble JNICALL Java_HelloJNI_avg(JNIEnv *, jobject, jint, jint);/** Class: HelloJNI* Method: myArray* Signature: ([I)[D*/
JNIEXPORT jdoubleArray JNICALL Java_HelloJNI_myArray(JNIEnv *, jclass, jintArray);#ifdef __cplusplus
}
#endif
#endif
然后在HelloJNI.cpp中实现相应函数
#include HelloJNI.h
#include iostream
#include jni.h
using namespace std;JNIEXPORT jstring JNICALL Java_HelloJNI_HelloWorld(JNIEnv *env, jobject obj){return env-NewStringUTF(JNI, hello world!);
} JNIEXPORT jdouble JNICALL Java_HelloJNI_avg(JNIEnv *env, jobject obj, jint a, jint b){return ((jdouble)ab)/2;
}JNIEXPORT jdoubleArray JNICALL Java_HelloJNI_myArray(JNIEnv *env, jclass obj, jintArray arr){// 获取Java整数数组的长度 jsize len env-GetArrayLength(arr); // 创建一个新的Java双精度浮点数数组 jdoubleArray result env-NewDoubleArray(len); if (result nullptr) { return nullptr; // 内存分配失败返回null } // 获取Java整数数组的元素 jint *intElements env-GetIntArrayElements(arr, nullptr); if (intElements nullptr) { return nullptr; // 内存分配失败返回null } // 设置Java双精度浮点数数组的元素 jdouble *doubleElements env-GetDoubleArrayElements(result, nullptr); if (doubleElements nullptr) { env-ReleaseIntArrayElements(arr, intElements, 0); // 释放整数数组元素 return nullptr; // 内存分配失败返回null应该处理异常但这里简化了 } // 执行转换 for (jsize i 0; i len; i) { doubleElements[i] intElements[i]; } // 释放数组元素 env-ReleaseDoubleArrayElements(result, doubleElements, 0); env-ReleaseIntArrayElements(arr, intElements, 0); // 返回转换后的数组 return result;
}编译链接运行
g -fpic -I$JAVA_HOME/include -I$JAVA_HOME/include/linux -shared -o libhello.so HelloJNI.cpp
java -Djava.library.path. HelloJNI结果