Skip to end of metadata
Go to start of metadata

You are viewing an old version of this content. View the current version.

Compare with Current View Version History

« Previous Version 6 Current »

This is a short checklist how Java and C++ code can synergize and how it is processed. All necessary steps are based on DWG Viewer.

  1. Java: Create a nativ method

  2. C++: Create a matching implementation

  3. Store the C++ implementation inside a shared library

  4. Compile the shared library with CMake

  5. Load the shared library with System.LoadLibrary()

  6. 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

JNI.java

public static native void SetBackgroundColor( int color );


2. C++: Create a matching implementation

ARESSimplified_JNI.cpp

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

Enable CMake compilation inside build.gradle file. Android Studio will take care about the necessary files and compiles everything with the NDK linked to the project.


build.gradle

...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()

To complete the Java and C++ synergy the shared library must be loaded into the host application once before any native method is called.

JNI.java

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

private void SetBackground( @BackgroundColor final int color )
{
    CFxARESInstance.instance().runOnWorkingThread(new Runnable()
    {
        @Override
        public void run()
        {
            JNI.SetBackgroundColor( color );
        }
    });
}
  • No labels