How to call Java functions from C++?

How can I call Java functions from a C++ application?

I know about calling them from CMD (or similar techniques), but I would rather not use them.


As an example, check Creating a JVM from C. It shows a sample procedure to create a JVM and invoke a method. If the JVM already exists; eg your C program is invoked by the Java program (callback situation), you can cache the JNIEnv* pointer.

As an advice, be careful caching pointers to the JVM from C/C++, there are some semantics involved as to what you can cache and it could be invoked later on. For that, as Brian Agnew pointed out, check the JNI reference.


Check out the JNI Invocation interface. This will allow you to embed a JVM within your C (or C++) application.

Note that various easier mechanisms exist to facilitate calling C/C++ from Java (eg JNA). It may be worth considering inverting your problem such that you can call from Java (I understand this may well not be possible for your particular application, however)


This page is helpful: http://hildstrom.com/projects/jni/index.html

Suppose you have a Java class:

package foo;
public class bar {
    public static int timesTen(int input){
        return input * 10;
    }
}

Once you have a JVM and JNIEnv* (details omitted...) you can invoke the Java method from C++ as follows:

jclass myClass = env->FindClass("foo.bar");
jmethodID mid = env->GetStaticMethodID(myClass, "timesTen", "(I)I");
jint hundred = env->CallStaticIntMethod(myClass, mid, (jint)10);

This glosses over a lot of detail, including exception handling, which if omitted will crash your JVM. For all the gory details search on "Java Native Interface" and follow the Oracle links.

链接地址: http://www.djcxy.com/p/17412.html

上一篇: Android中的ODEX文件是什么?

下一篇: 如何从C ++调用Java函数?