返回顶部

收藏

JNI: C 语言调用 Java 方法示例

更多

该程序用来演示在Linux下本地库如何调用JAVA方法编译方法: (其中$1为源文件名),需要根据自己机器的情况替换下面命令中指定的目录gcc -I /jdk/include -I /jdk/include/linux -L /jdk/jre/lib/i386 -ljava -lverify -L /jdk/jre/lib/i386/client -ljvm -L /jdk/jre/lib/i386/native_threads -lhpi $1作者: 刘柄成 (Winter Lau) 2004-1-26

jni_demo.c

#include <jni.h>
#include <stdio.h>
#include <stdlib.h>

#include <wchar.h> /* include the file to support unicode function */

const char*
DispatchStatus(int status)
{
    switch (status) {
        case JNI_OK:
            return "success";
            break;
        case JNI_ERR:
            return "unknown error";
            break;
        case JNI_EDETACHED:
            return "thread detached from the VM";
            break;
        case JNI_EVERSION:
            return "JNI version error";
            break;
        default:
            return __FILE__ ": unknow error";
            break;
    }
}

void
ArrayTest(JNIEnv* env)
{
    int i = 1;
    jintArray array = (*env)-> NewIntArray(env, 10);

    for(; i<= 10; i++)
        (*env)->SetIntArrayRegion(env, array, i-1, 1, &i);

    /* 获取数组对象的元素个数 */
    int len = (*env)->GetArrayLength(env, array);
    /* 获取数组中的所有元素 */
    jint* elems = (*env)-> GetIntArrayElements(env, array, 0);
    for(i=0; i< len; i++)
        printf("ELEMENT %d IS %d\n", i, elems[i]);
}

int
main(int argc, const char** argv)
{
    jint status = JNI_OK;
    JavaVM* jvm = (JavaVM*)0;
    JNIEnv* env = (JNIEnv*)0;

    JavaVMInitArgs vm_args;

    vm_args.version = JNI_VERSION_1_4;
    vm_args.options = (JavaVMOption*)0;
    vm_args.nOptions = 0;
    vm_args.ignoreUnrecognized = JNI_FALSE;

    status = JNI_GetDefaultJavaVMInitArgs(&vm_args);
    if (0 != status) {
        printf("%s\n", DispatchStatus(status));
        return EXIT_FAILURE;
    }

    status = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
    if (0 != status) {
        printf("test: %s\n", DispatchStatus(status));
        return EXIT_FAILURE;
    }
    printf("\r\n===== Array testing =====\r\n");
    ArrayTest(env);

    printf("test: success\n");
    if(jvm)
    (*jvm)->DestroyJavaVM(jvm);
    return EXIT_SUCCESS;
}

标签:JNI

收藏

0人收藏

支持

0

反对

0

发表评论