jni开发之返回值

最近工作需要利用到jni开发, 关于返回值这块内容, 稍微有点啰嗦, 结合自己查询的资料和开发的经验, 稍微整理了下.

文章内容分为两块: 简单返回值 和 复杂返回值

内容一. 简单返回值

指的是返回单一基本数据类型的数据.

1. 返回一个值

只需要知道Java基本数据类型与JNI数据类型的映射关系就可以了. 参照下表:

jni开发之返回值_第1张图片
图来源: https://blog.csdn.net/u011974987/article/details/52743495

在jni里, jni的数据类型和C/C++的数据类型可以互相赋值(参考下面代码)

...
double sksk = 10.0;
jdouble rst = 0;
rst = sksk;

return rst;

知道了对应关系, 我们返回对应类型即可, 也可以直接返回值.

`return 1.0; // 要求返回一个jdouble`
`return true; // 要求返回一个jboolean`

是不是感觉so easy?

2. 返回一个字符串

C/C++里面的字符串本质是字符数组, 所以处理是不一样的.
如果字符串内存是动态申请的, 别忘了释放.

char* tmpstr = new char[100];
sprintf(tmpstr , "%s", "this is a test"); // c语言中的字符串
jstring rtstr = env->NewStringUTF(tmpstr); // 转换成jni的jstring
delete[] tmpstr;
return rtstr; // 返回

3. 返回数组: 如果你需要返回多个值, 且是同种类型, 那么考虑下返回一个数组.

double output[3]; // 输出数据
...
jdoubleArray result = env->NewDoubleArray(3); // 返回用数组开辟内存
env->SetDoubleArrayRegion(result, 0, 3, output); // 把输出数据赋值进返回用数组里
return result; // 返回

jni里面每个类型的数组都是一个单独的类型, 比如有jdoubleArray, jbyteArray...
要返回一个数组, 只需要用对应的NewXXXArray函数和SetXXXArrayRegion函数初始化一个数组返回即可.

内容二. 复杂返回值, 返回一个类或者结构体

如果要返回好几个类型的值, 且数据类型各不相同, 这时候是不是想要是可以返回一个 "类 / 结构体" 就好了?
没问题, 继续往下看你就会了.

  1. 首先, 在.java文件中定义一个类, 用于返回数据.
public class ProcessResult {
    public int          width;
    public int          height;
    public double       H;
    public double       S;
    public double       V;
    public double[]     avgCon;
    public int          pixelsDataLength;
    public byte[]       pixelsData;

    public ProcessResult() {
        width = 0;
        height = 0;
    }
}
  1. .cpp的native代码里, 先要找到java里对应的类
jclass rstClass = env->FindClass("com/example/jfznkj/jianshu/ProcessResult"); // 搜索类
jmethodID initFunID = env->GetMethodID(rstClass, "", "()V"); // 获取构造函数
jobject result = env->NewObject(rstClass, initFunID); // 创建一个类的实例
  1. 找到类后对类的各个字段赋值
jfieldID temp  = env->GetFieldID(rstClass, "width", "I");
env->SetIntField(result, temp, width);

temp = env->GetFieldID(rstClass, "height", "I");
env->SetIntField(result, temp, height);

temp = env->GetFieldID(rstClass, "H", "D");
env->SetDoubleField(result, temp, tempH);

temp = env->GetFieldID(rstClass, "S", "D");
env->SetDoubleField(result, temp, tempS);

temp = env->GetFieldID(rstClass, "V", "D");
env->SetDoubleField(result, temp, tempV);

jdoubleArray avgArray = env->NewDoubleArray(25);
env->SetDoubleArrayRegion(avgArray, 0, 25, avg);
temp = env->GetFieldID(rstClass, "avgCon", "[D");
env->SetObjectField(result, temp, avgArray);

temp = env->GetFieldID(rstClass, "pixelsDataLength", "I");
env->SetIntField(result, temp, picDataLength);

jbyteArray picArray = env->NewByteArray(picDataLength);
env->SetByteArrayRegion(picArray, 0, picDataLength, picData);
temp = env->GetFieldID(rstClass, "pixelsData", "[B");
env->SetObjectField(result, temp, picArray);

return result ;

简单的总结, 先搜索到字段地址, 再往里赋准备好的jni数据, 数据如何准备参照 [内容一]
实例各个字段都初始化完毕, 就可以返回一个类拉.
对了, 不管什么类, 都对应jni里都是jobject类型.

最后贴一个我函数的完整代码

// 该函数包含所有的图片处理
// 1. 图片画素数组取出
// 2. hsv计算
// 3. 灰度计算
// 4. 平均浓度计算
// 5. nv21数据类型转换
extern "C" JNIEXPORT jobject JNICALL Java_com_example_jfznkj_jianshu_MainActivity_MuptiplePictureProcessingForSpeedUp
        (JNIEnv *env, jobject jobj, jbyteArray data_, jint width, jint height){
    jbyte * data = env->GetByteArrayElements(data_, NULL);

    // 耀哥灰度
    int greyThreshold = 800;            //灰度阈值
    int diffThreshold = 8;              //差值阈值
    int startX = width / 4;
    int endX = width * 3 / 4;
    int startY = height / 4;
    int endY = height * 3 / 4;
    int grey;
    int maxDiff;                        //r g b 中最大差值
    int sumNum = 0;                        //灰度大于greyThreshold的像素点总数
    int tarNum = 0;                     //r g b 最大差值小于diffThreshold的像素点数;

    // hsv计算
    double dblH = 0.0, dblS = 0.0, dblV = 0.0;
    int colorHArr[361] = {0};

    // 浓度计算
    int avgConLength = 25;
    int avgConStartPos = 6;
    double avgConSum[25] = {0.0};
    int avgConCnt[25] = {0};
    int avgBlockW = width / 5;
    int avgBlockH = height / 5;
    double avg[25];

    int allConLength = 9;
    int allConStartPos = avgConStartPos + avgConLength + 1;
    double allConSum[9] = {0.0};
    int allConCnt[9] = {0};
    int allBlockW = width / 3;
    int allBlockH = height / 3;
    double all[9];

    // NV21转换
    int nv21Length = width * height * 3 / 2;
    jbyte* nvData = new jbyte[nv21Length];

    // 图像数据
    int picDataLength = width * height * 3;
    jbyte* picData = new jbyte[picDataLength];
    int tempPicDataIdx = 0;


    // 循环
    jbyte* pNV12 = nvData;

    for (int y = 0; y < height; y++) {
        // nv21转换
        jbyte* pY = pNV12 + y * width;
        jbyte*pCrCb = pNV12 + (width * height) + (y >> 1) * width;

        for (int x = 0; x < width; x++) {
            //unsigned char colorB = pixels[y * step + x * chan + 0];
            //unsigned char colorG = pixels[y * step + x * chan + 1];
            //unsigned char colorR = pixels[y * step + x * chan + 2];

            unsigned char colorB = data[y * width * 3 + x * 3 + 0];
            unsigned char colorG = data[y * width * 3 + x * 3 + 1];
            unsigned char colorR = data[y * width * 3 + x * 3 + 2];

            // 图片画素数组取出
            picData[tempPicDataIdx] = colorB; tempPicDataIdx++;
            picData[tempPicDataIdx] = colorG; tempPicDataIdx++;
            picData[tempPicDataIdx] = colorR; tempPicDataIdx++;

            // hsv
            if (y % 3 == 0 && x % 3 == 0) {
                double B = (double) colorB;
                double G = (double) colorG;
                double R = (double) colorR;
                double _max = MAXHSV(B, G, R);
                double _min = MINHSV(B, G, R);
                dblV += _max;
                if (std::abs(_max - _min) <= 0.000001) {
                    dblS += 0;
                } else {
                    dblS += (_max - _min) / _max * 100.0;
                }
                if (std::abs(_max - _min) <= 0.000001) {
                    dblH = 0.0;
                } else {
                    if (std::abs(R - _max) <= 0.000001 && G >= B)
                        dblH = (G - B) / (_max - _min) * 60;
                    else dblH = (G - B) / (_max - _min) * 60 + 360;

                    if (std::abs(G - _max) <= 0.000001) dblH = 120 + (B - R) / (_max - _min) * 60;
                    if (std::abs(B - _max) <= 0.000001) dblH = 240 + (R - G) / (_max - _min) * 60;
                }
                int nH = (int) dblH;
                colorHArr[nH]++;
            }

            // 浓度计算
            int tempAvgIdx = y / avgBlockH * 5 + x / avgBlockW;
            avgConSum[tempAvgIdx] += (colorB + colorG + colorR);
            avgConCnt[tempAvgIdx] ++;

            int tempAllIdx = y / allBlockH * 3 + x / allBlockW;
            allConSum[tempAllIdx] += (colorB + colorG + colorR);
            allConCnt[tempAllIdx] ++;

            // nv21转换
            int Y;
            int Cb;
            int Cr;

            Y = (1225 * colorR + 2404 * colorG + 467 * colorB) >> 12;
            *pY = NV21_CLAMP_INT32_8(Y);
            pY++;
            if ((x & 0x00000001) == 0x00000000) {
                Cr = (524288 + 2048 * colorR - 1715 * colorG - 333 * colorB) >> 12;
                Cb = (524288 - 691 * colorR - 1357 * colorG + 2048 * colorB) >> 12;
                *pCrCb = NV21_CLAMP_INT32_8(Cr);
                pCrCb++;
                *pCrCb = NV21_CLAMP_INT32_8(Cb);
                pCrCb++;
            }

            // 耀哥灰度
            if ( x >= startX && x < endX && y >= startY && y < endY  && y % 2 == 0 && x % 2 == 0) {
                grey = 3 * colorR + 6 * colorG + colorB;//(int)(0.30 * R + 0.59 * G + 0.11 * B);
                if (grey > greyThreshold) {
                    sumNum++;
                    maxDiff = abs(colorR - colorG);
                    if (maxDiff > diffThreshold) continue;
                    maxDiff = abs(colorR - colorB);
                    if (maxDiff > diffThreshold) continue;
                    maxDiff = abs(colorB - colorG);
                    if (maxDiff > diffThreshold) continue;
                    tarNum++;
                }
            }
        }
    }

    // 耀哥灰度
    double tempGreyValue = 0.0;
    if(sumNum > 10) tempGreyValue = (float)tarNum / (float)sumNum;

    // hsv
    int average = 0;
    int hsvCnt = 0;
    for (int i = 0; i < 361; i++) {
        average += colorHArr[i] * i;
        hsvCnt += colorHArr[i];
    }
    average = average / hsvCnt;

    double variance = 0.0;
    for (int i = 0; i < 361; i++) {
        variance += (i - average) * (i - average) * colorHArr[i];
    }
    double tempH = variance / hsvCnt; // H
    double tempS = dblS / hsvCnt; // S
    double tempV = dblV / hsvCnt; // V

    // 浓度计算
    for (int i = 0; i < avgConLength; i++) {
        avg[i] = avgConSum[i] / (double)avgConCnt[i];
    }

    for (int i = 0; i < allConLength; i++) {
        all[i] = allConSum[i] / (double)allConCnt[i];
    }

    env->ReleaseByteArrayElements(data_, data, 0);

    jclass rstClass = env->FindClass("com/example/jfznkj/jianshu/ProcessResult");
    jmethodID initFunID = env->GetMethodID(rstClass, "", "()V");
    jobject result = env->NewObject(rstClass, initFunID);

    jfieldID temp  = env->GetFieldID(rstClass, "width", "I");
    env->SetIntField(result, temp, width);

    temp = env->GetFieldID(rstClass, "height", "I");
    env->SetIntField(result, temp, height);

    temp = env->GetFieldID(rstClass, "grey", "D");
    env->SetDoubleField(result, temp, tempGreyValue);

    temp = env->GetFieldID(rstClass, "H", "D");
    env->SetDoubleField(result, temp, tempH);

    temp = env->GetFieldID(rstClass, "S", "D");
    env->SetDoubleField(result, temp, tempS);

    temp = env->GetFieldID(rstClass, "V", "D");
    env->SetDoubleField(result, temp, tempV);

    jdoubleArray avgArray = env->NewDoubleArray(25);
    env->SetDoubleArrayRegion(avgArray, 0, 25, avg);
    temp = env->GetFieldID(rstClass, "avgCon", "[D");
    env->SetObjectField(result, temp, avgArray);

    jdoubleArray allArray = env->NewDoubleArray(9);
    env->SetDoubleArrayRegion(allArray, 0, 9, all);
    temp = env->GetFieldID(rstClass, "allCon", "[D");
    env->SetObjectField(result, temp, allArray);

    temp = env->GetFieldID(rstClass, "NV21DataLength", "I");
    env->SetIntField(result, temp, nv21Length);

    jbyteArray nvArray = env->NewByteArray(nv21Length);
    env->SetByteArrayRegion(nvArray, 0, nv21Length, nvData);
    temp = env->GetFieldID(rstClass, "NV21Data", "[B");
    env->SetObjectField(result, temp, nvArray);

    temp = env->GetFieldID(rstClass, "pixelsDataLength", "I");
    env->SetIntField(result, temp, picDataLength);

    jbyteArray picArray = env->NewByteArray(picDataLength);
    env->SetByteArrayRegion(picArray, 0, picDataLength, picData);
    temp = env->GetFieldID(rstClass, "pixelsData", "[B");
    env->SetObjectField(result, temp, picArray);

    delete[] nvData;
    delete[] picData;
    return result;

}

关于jni返回值, 就介绍到这里.

你可能感兴趣的:(jni开发之返回值)