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

Hem*_*ant 28 c c++ java

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

Mic*_*ker 44

是的,你可以,但它有点复杂,并以反射/非类型安全的方式工作(例如使用比C版本更清洁的C++ api).在这种情况下,它从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();
}
Run Code Online (Sandbox Code Playgroud)

要编译(在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
Run Code Online (Sandbox Code Playgroud)

注意:应该检查每个方法的返回代码,以便实现正确的错误处理(为方便起见,我忽略了这一点).例如

str = env->GetStringUTFChars(jstr, NULL);
if (str == NULL) {
    return; /* out of memory */
}
Run Code Online (Sandbox Code Playgroud)


CB *_*ley 9

是的,但你必须通过JNI这样做:http://java.sun.com/javase/6/docs/technotes/guides/jni/index.html

  • 我见过 JNI 用于从 Java 调用 C++。不知道它也以其他方式起作用。 (3认同)
  • 奇怪的是,我一直认为它更常用于从Java提供对C++库的访问,但它有两种方式. (3认同)