NDK开发之数组参数和数组返回值

时间:2021-09-03 00:26:25

本文为作者(石岩)原创,转载请指明出处:
https://blog.csdn.net/a1002450926/article/details/79800440

Java代码演示

public class JniTest {

    // 传入数组排序
    public native void giveArray(int[] array);

    // 返回数组
    public native int[] getArray(int len);

    public static void main(String[] args) {
        int[] array = new int[] { 1, 100, 3, 40, 24, 89 };
        JniTest test = new JniTest();

        test.giveArray(array);

        for (int i : array) {
            System.out.println(i);
        }

        System.out.println("-------------------------------");

        int[] array2 = test.getArray(10);

        for (int i : array2) {
            System.out.println(i);
        }
    }

    static {
        System.loadLibrary("JniTest");
    }
}

C代码演示

#pragma once
#pragma execution_character_set("utf-8")

#define _CRT_SECURE_NO_WARNINGS
#include "com_shiyan_jni_JniTest.h"
#include<stdlib.h>

/* 传入数组 */
int compare(int *a, int *b);

JNIEXPORT void JNICALL Java_com_shiyan_jni_JniTest_giveArray
(JNIEnv *env, jobject jobj, jintArray arr){
    //jintArray -->jint指针-->c int数组
    jint *elems = (*env)->GetIntArrayElements(env, arr, JNI_FALSE);

    //数组的长度
    int len = (*env)->GetArrayLength(env, arr);

    //排序
    qsort(elems, len, sizeof(jint), compare);

    //mode
    //0 JAVA数组进行更新,并且释放C/C++数组
    //JNI_ABORT JAVA数组不进行更新,但是释放C/C++数组
    //JNI_COMMIT JAVA数组进行更新,不释放C/C++数组(函数执行完,数组还是会释放)
    //同步
    (*env)->ReleaseIntArrayElements(env, arr, elems, 0);
}

/* 返回数组 */
JNIEXPORT jintArray JNICALL Java_com_shiyan_jni_JniTest_getArray
(JNIEnv *env, jobject jobj, jint len){
    jintArray jint_arr = (*env)->NewIntArray(env, len);
    jint *elems = (*env)->GetIntArrayElements(env, jint_arr, JNI_FALSE);

    for (int i = 0; i < len; i++){
        elems[i] = i;
    }

    //同步
    (*env)->ReleaseIntArrayElements(env, jint_arr, elems, 0);

    return jint_arr;
}

int compare(int *a, int *b){
    return *a - *b;
}

结果演示

NDK开发之数组参数和数组返回值