【Android】 C/C++ 标准输入输出打印至Android日志控制台
#if defined(__ANDROID__)
start_logger("yeasound_sdk-native");
#endif#if defined(__ANDROID__)
#include <stdio.h>
#include <unistd.h>
#include <android/log.h>
#include <android/native_activity.h>
#include <android/asset_manager_jni.h>
#include <android/asset_manager.h>
#endif#if defined(__ANDROID__)
extern "C" {static int pfd[2];static pthread_t thr;static const char *tag = "myapp";static void *thread_func(void *){ssize_t rdsz;char buf[128];while ((rdsz = read(pfd[0], buf, sizeof buf - 1)) > 0) {if (buf[rdsz - 1] == '\n') --rdsz;buf[rdsz] = 0; /* add null-terminator */__android_log_write(ANDROID_LOG_DEBUG, tag, buf);}return 0;}int start_logger(const char *app_name){tag = app_name;/* make stdout line-buffered and stderr unbuffered */setvbuf(stdout, 0, _IOLBF, 0);setvbuf(stderr, 0, _IONBF, 0);/* create the pipe and redirect stdout and stderr */pipe(pfd);dup2(pfd[1], 1);dup2(pfd[1], 2);/* spawn the logging thread */if (pthread_create(&thr, 0, thread_func, 0) == -1)return -1;pthread_detach(thr);return 0;}
}
#endifJNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved)
{JNIEnv *env;if (vm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6) != JNI_OK) {return JNI_ERR;}#if defined(__ANDROID__)start_logger("yeasound_sdk-native");
#endif/* --javaVM是虚拟机在JNI中的表示 --*/env->GetJavaVM(&g_jni_vm);if (g_jni_vm == nullptr) {return JNI_ERR;}jni_utils_set_global_vm(g_jni_vm);if(jni_cache_init() != YeasoundLib::YS_STATUS_SUCCESS){return JNI_ERR;}return JNI_VERSION_1_6;
}