Android - How can I Call C++ methods from Java?

October 17, 2012 - 1:00pm #1

The Vuforia Android samples are set up such that application lifecycle events are handled in Java, but tracking events and rendering are handled natively in C++. Additionally, users may want to leverage Android SDK functionality (such as touch handling or networking logic) while doing the low-level graphics work natively. All this requires that we have a means of communicating between Java and C++. This is provided by the JNI (Java Native Interface).

For a practical example of using the JNI to respond to native tracking events in Java see this article: https://ar.qualcomm.at/content/how-can-i-update-my-android-ui-response-tracking-events

Calling native methods from Java

All of the Vuforia samples make a few JNI calls out of the box. In ImageTargets.java, look for method declarations starting with "public native".

For example:

public native int initTracker();

This method is defined in ImageTargets.cpp as follows:

#include <jni.h>

#ifdef __cplusplus

extern "C"

{

#endif

JNIEXPORT int JNICALL Java_com_qualcomm_QCARSamples_ImageTargets_ImageTargets_initTracker(JNIEnv *, jobject)

{

...

}

#ifdef __cplusplus

}

#endif

First, note that all JNI methods exposed in C++ are wrapped in an extern "C" block. The function return type must be surrounded by the JNIEXPORT and JNICALL macros. Then the function name takes the form Java_package_class_function. We are effectively implementing the method that we defined in Java. From Java, you can call this method like any other Java method:

int result = initTracker();

Topic locked