How to call Java methods from C ++ in JNI

So, I am writing an Android application that uses a large C ++ library. Everything works for me so that the java application can call C ++ delegation methods, but I want it so that I can write messages from C ++ to the Android log. This is easy from java, but I donโ€™t understand how to call the java method from C ++. My searches found methods for opening jvm from C ++, which is not at all what I want to do. Ideally, I would like to pass a C ++ log method pointer, which I could then use whenever I wanted. Of course, java does not support method pointers. My java method will look something like this:

private void log(String s){ Log.i(Tag, s); // Android log } 

I just don't know how to allow C ++ to access this method.

+1
java c ++ android android-ndk jni
Oct 10 2018-10-10
source share
2 answers

C ++ calls to cout and printf will not appear in LogCat output. There are two solutions.

  • Use the logging macros provided by the NDK that allow you to log messages in LogCat. This is useful for new code and shell code that you write, but not so good when you have a library full of existing debug statements. I define macros as follows:

     #define LOG_INFO(info) __android_log_write(ANDROID_LOG_INFO,"JNI",info) #define LOG_ERROR(error) __android_log_write(ANDROID_LOG_ERROR,"JNI",error) 

    and then in the source code I can call LOG_INFO("Library is called!");

  • Grab the standard error / standard error of the program and move it to LogCat. From the Android Debug Bridge page:

    View stdout and stderr

    By default, the Android system sends the stdout and stderr outputs (System.out and System.err) to / dev / null. In processes that run Dalvik VM, you can write a copy of the log file to the system. In this case, the system writes messages to the log using the log tags stdout and stderr, both with priority I.

    To route output in this way, you stop the emulator / device instance from starting, and then use the shell setprop command to enable output redirection. Here's how you do it:

      $ adb shell stop $ adb shell setprop log.redirect-stdio true $ adb shell start 

    The system saves this parameter until you finish the emulator / device instance. To use the default option in the emulator / device instance, you can add an entry to /data/local.prop on the device.

+6
Oct 10 '10 at
source share

Logging is placed in the header file '#include'.

To link .so, put 'LOCAL_LDLIBS: = -L $ (SYSROOT) / usr / lib -llog' in your make file.

0
Oct 10 2018-10-10
source share



All Articles