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; e.g. 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 (e.g. 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.

Since someone asked... here's how you get an Env*. Note that if the JVM called your native code, it will already have an Env*.

JNIEnv* env(0);
jint rv = vm->GetEnv((void**)&env, JNI_VERSION_1_6);
if (rv == JNI_OK) {
    return env;
} else if (rv == JNI_EDETACHED) {
    // This happens if you created the thread, not the JVM
    rv = vm->AttachCurrentThread((void**)&env, 0);
    if (rv != JNI_OK) {
        // error
    }
} else {
    // error
}

I cannot stress enough that using JNI to call Java from C/C++ is tremendously tedious and error-prone. Errors are cryptic and low-level. You must handle exceptions, and you must detach threads or things will get ugly.