如何在 C++ 应用程序中访问 Java 方法 [英] How to access the Java method in a C++ application

查看:28
本文介绍了如何在 C++ 应用程序中访问 Java 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Just a simple question: Is it possible to call a java function from c/c++ ?

推荐答案

是的,你可以,但它有点复杂,并且以反射/非类型安全的方式工作(示例使用 C++ api,它比C 版本).在这种情况下,它会从 C 代码中创建 Java VM 的一个实例.如果您的本机代码首先从 Java 调用,则无需构建 VM 实例

Yes you can, but it is a little convoluted, and works in a reflective/non type safe way (example uses the C++ api which is a little cleaner than the C version). In this case it creates an instance of the Java VM from within the C code. If your native code is first being called from Java then there is no need to construct a VM instance

#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
", str);

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

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

编译(在 Ubuntu 上):

To compile (on 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

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

Note: that the return code from each of these methods should be checked in order to implement correct error handling (I've ignored this for convenience). E.g.

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

这篇关于如何在 C++ 应用程序中访问 Java 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆