代码改变世界

jni c++调用java

2012-08-03 19:45  o-lijin-o  阅读(247)  评论(0编辑  收藏  举报

 1. jvm.dll要在环境变量PATH,例如 ...;D:\java\sdk6\jre\bin\client

 2. 需要的jar要合并为一个

 

    B=byte
    C=char
    D=double
    F=float
    I=int
    J=long
    S=short
    V=void
    Z=boolean
    Lfully-qualified-class=fully qualified class
    [type=array of type>
    (argument types)return type=method type. If no arguments, use empty argument types: (). If return type is void (or constructor) use (argument types)V.

 

void test02()
{
    JNIEnv *env;
    JavaVM *jvm;
    jint res;
    JavaVMInitArgs vm_args;

    vm_args.version = JNI_VERSION_1_6;
    vm_args.options = 0;
    vm_args.nOptions = 0;
    vm_args.ignoreUnrecognized = JNI_TRUE;
   

    res = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args );

    printf( "JNI_CreateJavaVM %d\n", res );

    if ( res != 0 )
        return;

    jclass j_system = env->FindClass("java/lang/System");
    jfieldID j_system_out_id = env->GetStaticFieldID( j_system, "out", "Ljava/io/PrintStream;");
    jobject j_system_out = env->GetStaticObjectField( j_system, j_system_out_id );
    jclass j_system_out_class = env->GetObjectClass(j_system_out);
    jmethodID j_system_out_println = env->GetMethodID( j_system_out_class, "println", "(Ljava/lang/String;)V" );
    jstring val = env->NewStringUTF("call from c++");
    env->CallVoidMethod( j_system_out, j_system_out_println, val );

    if ( jvm )
        (jvm)->DestroyJavaVM();
}