一尘不染

如何在C ++应用程序中访问Java方法

java

只是一个简单的问题:是否可以从c / c ++调用Java函数?


阅读 256

收藏
2020-03-24

共1个答案

一尘不染

是的,你可以,但是它有点令人费解,并且以反射/非类型安全的方式工作(示例使用的C ++ API比C版本更干净)。在这种情况下,它将从C代码中创建Java VM的实例。如果首先从Java调用你的本机调用,则无需构造VM实例

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

int main(int argc, char** argv) {

    JavaVM *vm;
    JNIEnv *env;
    JavaVMInitArgs vm_args;
    vm_args.version = JNI_VERSION_1_2;
    vm_args.nOptions = 0;
    vm_args.ignoreUnrecognized = 1;

    // Construct a VM
    jint res = JNI_CreateJavaVM(&vm, (void **)&env, &vm_args);

    // Construct a String
    jstring jstr = env->NewStringUTF("Hello World");

    // First get the class that contains the method you need to call
    jclass clazz = env->FindClass("java/lang/String");

    // Get the method that you want to call
    jmethodID to_lower = env->GetMethodID(clazz, "toLowerCase",
                                      "()Ljava/lang/String;");
    // Call the method on the object
    jobject result = env->CallObjectMethod(jstr, to_lower);

    // Get a C-style string
    const char* str = env->GetStringUTFChars((jstring) result, NULL);

    printf("%s\n", str);

    // Clean up
    env->ReleaseStringUTFChars(jstr, str);

    // Shutdown the VM.
    vm->DestroyJavaVM();
}

编译(在Ubuntu上):

g++ -I/usr/lib/jvm/java-6-sun/include \ 
    -I/usr/lib/jvm/java-6-sun/include/linux \ 
    -L/usr/lib/jvm/java-6-sun/jre/lib/i386/server/ -ljvm jnitest.cc

注意:为了实现正确的错误处理,应检查每种方法的返回代码(为方便起见,我将其忽略了)。例如

str = env->GetStringUTFChars(jstr, NULL);
if (str == NULL) {
    return; /* out of memory */
}
2020-03-24