views:

121

answers:

2

So I'm writing an Android app which uses a large c++ library. I have everything working so that the java app can call the c++ delegation methods, but I'm finding myself wishing I could log messages from c++ to the Android log. This is easy from java, but I'm at a loss as to how to call a java method from c++. My searches found methods for opening a jvm from c++, which is not at all what I want to do. Ideally, I'd like to pass a log method pointer to c++, which could then be used whenever I wanted. Of course, java doesn't support method pointers. My java method would look something like:

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

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

A: 

Logging is placed at '#include ' header file.

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

Damian Kołakowski
+3  A: 

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

  1. Use the Logging macros provided by the NDK that allow you to log messages to LogCat. This is good for new code and wrapper code you are writing, but not so good when you have a library full of existing debugging statements. See this post for the full story. I define macros as followed:

    #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 within the sourcecode I can call LOG_INFO("Library is called!");

  2. Capture the standard out/ standard error of the program and funnel it into LogCat. From the Android Debug Bridge page:

    Viewing stdout and stderr

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

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

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

    The system retains this setting until you terminate the emulator/device instance. To use the setting as a default on the emulator/device instance, you can add an entry to /data/local.prop on the device.

I82Much
This is exactly what I wanted. I added a "local.prop" file to the /data/ folder on the emulator with the line: log.redirect-stdio=trueAnd I'm getting stdout to the log.
erock2112