天天看点

Java JNI 入门篇——传递数组与修改数组

package com.example.jni;

public class ArrayJNI {
    static {
        System.loadLibrary("arrayjni");
    }

    public native byte[] process(byte[] data);

    public static void main(String[] args) throws Exception {
        byte[] srcbyte = new byte[] { 1, 2, 3 };
        ArrayJNI item = new ArrayJNI();
        byte[] resultbyte = item.process(srcbyte);
        System.out.print("(Java)result byte: ");
        for (int i = 0; i < resultbyte.length; i++) {
            System.out.printf("%d\t", 0xff & resultbyte[i]);
        }
        System.out.println();
    }

}
           
// arrayjni.cpp : Defines the exported functions for the DLL application.
//

#include "stdafx.h"
#include "com_example_jni_ArrayJNI.h"
#include <iostream>
/*
* Class:     com_example_jni_ArrayJNI
* Method:    process
* Signature: ([BII)[B
*/
JNIEXPORT jbyteArray JNICALL Java_com_example_jni_ArrayJNI_process
(JNIEnv * env, jobject obj, jbyteArray byteArray) {
    jbyte* receivedbyte = env->GetByteArrayElements(byteArray, 0);
    jsize size = env->GetArrayLength(byteArray);
    printf("(C++) received byte: ");

    for (int i = 0; i < size; i++) {
        int value = (int)(receivedbyte[i] & 0xff);
        printf("%d\t",value);
        jbyte v = (~value);

        env->SetByteArrayRegion(byteArray, i, 1, &v);
    }

    return byteArray;

}