...
Java: Create a nativ method
C++: Create a matching implementation
Store the C++ implementation inside a shared library
Compile the shared library with CMake
Load the shared library with System.LoadLibrary()
Call the JNI method
Note: When a Java native method is called before the implementation is loaded it leads to a crash!
More details about more complex data transfer can be found in the following topics:
Low level: C++ and JNI data transfer
High level: C++ and JNI data transfer
1. Java: Create a nativ method
...
Code Block | ||
---|---|---|
| ||
public static native void SetBackgroundColor( int color ); |
2. C++: Create a matching implementation
...
Code Block |
---|
JNIEXPORT void JNICALL Java_com_graebert_aressimplified_JNI_SetBackgroundColor( JNIEnv * env, jclass clazz, jint color ){...} |
3. Store the C++ implementation inside a shared library
See CFx/AndroidSimplified_JNI/app/CMakeLists.txt
See CFx/CMakeLists.txt
4. Compile the shared library with CMake
...
Code Block |
---|
...externalNativeBuild { cmake { arguments "-DANDROID_STL=c++_shared", "-DVIEWER=1" cppFlags "-std=c++11 -frtti -fexceptions" } } ... externalNativeBuild { cmake { path file('../../CMakeLists.txt') } } ... |
5. Load the shared library with System.LoadLibrary()
...
Code Block | ||
---|---|---|
| ||
public static void Load()
{
String lib = "";
try
{
lib = "JNI"; System.loadLibrary(lib);
}
catch (UnsatisfiedLinkError use)
{
Log.e("JNI", "WARNING: Could not load JNI library " + lib, use );
}
...
} |
6. Call the JNI method
Whenever you call a JNI method from the app part of your application, you need to run it from the working thread. The class CFxARESInstance provides the method runOnWorkingThread() for this purpose.
MainActivity.java
Code Block |
---|
private void SetBackground( @BackgroundColor final int color )
{
CFxARESInstance.instance().runOnWorkingThread(new Runnable()
{
@Override
public void run()
{
JNI.SetBackgroundColor( color );
}
});
} |