JNI 中操作Activity 中的数组(笔记)

2023-11-20  本文已影响0人  红鲤鱼与绿鲤鱼与驴与鱼
#include <jni.h>
#include "logTool.h"
#include <cstdlib>

//函数指针 int (*__comparator)(const void* __lhs, const void* __rhs)
jint compare(const jint *a, const jint *b) {
//    const int *a1 = static_cast<const int *>(a);
//    const int *b1 = static_cast<const int *>(b);
    LOGE("a1:%d, b1:%p",*a,&b);//*a 取值, &b取地址
    return *a - *b;
}

//表态注册
extern "C"
JNIEXPORT void JNICALL
Java_cn_ztx_kotlindemo2_MainActivity_sort(JNIEnv *env, jobject thiz, jintArray arr) {
    jint *pInt = env->GetIntArrayElements(arr, nullptr);
    jsize size = env->GetArrayLength(arr);
//(void* __base, size_t __nmemb, size_t __size, int (*__comparator)(const void* __lhs, const void* __rhs));

    //排序操作,此方法在 stdlib.h 中
    qsort(pInt, size, sizeof(int), reinterpret_cast<int (*)(const void *, const void *)>(compare));
    
     /**
     * 0:           刷新Java层,并释放 C++ 数组
     * JNI_COMMIT:  只提交,只刷新Java层,不释放C++ 数组
     * JNI_ABORT:   只释放C++ 数组
     */
    env->ReleaseIntArrayElements(arr,pInt,0);
}

必须使用 env->ReleaseIntArrayElements 方法来刷新Java层的数组,并且释放C++的数组

上一篇 下一篇

猜你喜欢

热点阅读