2013년 7월 31일 수요일

JNI int,String array parameter, return value

int array를 parameter로 넘겨기 예제(java->jni)

---------------------------------------------------------------------------------------
java file

public class Test {
    static {
        System.loadLibrary("test");
    }

    public static void func1(int arr[]) {
        native_func1(core);
    }

 private native static void native_func1(int arr[]);


---------------------------------------------------------------------------------------
cpp file

static void native_func1(JNIEnv* env, jobject obj, jintArray arr) {
    int size = env->GetArrayLength(arr);

    jint *value = env->GetIntArrayElements(arr, NULL);

    for (int i = 0; i < size; i++) {
        value[i] = i;
    }
 
    env->ReleaseIntArrayElements(arr, value, 0);
    return;
}

static const JNINativeMethod g_methods[] = { 
    { "native_func1", "([I)V", (void*)native_func1 }, 
}; 
  
---------------------------------------------------------------------------------------
//배열 생성 
int[] arr = new int[4];
//배열 전달
Test.func1(arr);


String array를 return value로 받기(jni->java)

---------------------------------------------------------------------------------------
java file
static jobjectArray native_func2(JNIEnv* env, jobject obj) {
    char *temp[4] = { "apple, "banana", tomato", "melon"};

    jobjectArray ret = (jobjectArray)env->NewObjectArray(4, env->FindClass("java/lang/String"),
            env->NewStringUTF(""));

    for (int i = 0; i < 4; i++) {
        env->SetObjectArrayElement(ret, i, env->NewStringUTF(temp[i]));
    }
    return ret;
}

static const JNINativeMethod g_methods[] = {
    { "native_func2", "()[Ljava/lang/String;", (jobjectArray*)native_func2 },
};


---------------------------------------------------------------------------------------
java file

public class Test {
    static {
        System.loadLibrary("test");
    }

    public static String[] func2() {
        return native_func2();
    }

    private native static String[] native_func2();



---------------------------------------------------------------------------------------
String[] str = new String[4];
str = Test.func2();
댓글 쓰기