如何解决如何在JNI NDK Android中正确且简单地使用回调函数
我正在尝试让Java在Android中调用C函数,但我遇到的一些警告是,关于回调的文档通常似乎非常不清楚,因此,关于SO的大多数答案都只是在谈论理论并发布没有实际联系的断开链接码。因此,请在您的答案中发布代码。
我正在尝试用Java创建操纵杆并将其发送到NDK以便执行操作。
- 如果我可以让Java调用C函数并将int传递给它, 那会很好。但我认为这行不通,因为C正在运行 这是自己的主循环。
- 也许我需要使用C来调用Java 函数来获取控制器状态并从那里执行代码。
我确实设法找到了一些代码Here,但看起来该代码虽然可以自行编译,但在移至现代代码后似乎无法正常工作。
如何在Android上以Java C关系实现回调?从上面的代码示例中可以看出,正是C调用了Java函数,这些函数需要像getters函数一样使用。
这里有一些代码,我似乎丢失了一些东西,因为我不清楚我应该如何执行这些回调。如果使用Java或C ++(CPP),我将在此代码中标注函数名称及其位置。
我认为有两种方法可以使它工作。
我要调用的Java函数
public int Cat(){
Log.e("JniHandler","CAT WAS CALLED!!!");
return 333;
}
结构信息CPP。不知道是否需要。
#include <string.h>
#include <inttypes.h>
#include <pthread.h>
#include <jni.h>
#include <android/log.h>
#include <assert.h>
typedef struct tick_context {
JavaVM *javaVM;
jclass jniHelperClz;
jobject jniHelperObj;
jclass mainActivityClz;
jobject mainActivityObj;
pthread_mutex_t lock;
int done;
} TickContext;
TickContext g_ctx;
本节有效。看起来,一旦启动JVM,它就会初始化。
JNI_OnLoad CPP
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm,void* reserved) {
JNIEnv* env;
memset(&g_ctx,sizeof(g_ctx));
SDL_Log(" DEBUG -- JNI INIT!!!");
g_ctx.javaVM = vm;
if (vm->GetEnv((void**)&env,JNI_VERSION_1_6) != JNI_OK) {
return JNI_ERR; // JNI version not supported.
}
jclass clz = env->FindClass("org/foo/bar/mainactivity");
g_ctx.jniHelperClz = (jclass)env->NewGlobalRef(clz); // hack
jmethodID jniHelperCtor = env->GetMethodID(g_ctx.jniHelperClz,"<init>","()V");
jobject handler = env->NewObject(g_ctx.jniHelperClz,jniHelperCtor);
g_ctx.jniHelperObj = env->NewGlobalRef(handler);
//queryRuntimeInfo(env,g_ctx.jniHelperObj); // This when getting version returns null.
g_ctx.done = 0;
g_ctx.mainActivityObj = NULL;
return JNI_VERSION_1_6;
}
queryRuntimeInfo CPP
void queryRuntimeInfo(JNIEnv *env,jobject instance) {
SDL_Log("DEBUG QUERYRUNTIME INTO");
// Find out which OS we are running on. It does not matter for this app
// just to demo how to call static functions.
// Our java JniHelper class id and instance are initialized when this
// shared lib got loaded,we just directly use them
// static function does not need instance,so we just need to feed
// class and method id to JNI
jmethodID versionFunc = env->GetStaticMethodID(g_ctx.jniHelperClz,"getBuildVersion","()Ljava/lang/String;"); // This returns null.
if (!versionFunc) {
SDL_Log("DEBUG versionFunc INTO");
//LOGE("Failed to retrieve getBuildVersion() methodID @ line %d",__LINE__);
return;
}
SDL_Log("DEBUG BUILD VERSION INTO");
jstring buildVersion = (jstring)env->CallStaticObjectMethod(g_ctx.jniHelperClz,versionFunc); // hack
const char *version = env->GetStringUTFChars(buildVersion,NULL);
if (!version) {
SDL_Log("DEBUG buildVersion INTO");
//LOGE("Unable to get version string @ line %d",__LINE__);
return;
}
//LOGI("Android Version - %s",version);
SDL_Log("DEBUG ANDROID VERSION %s",version);
env->ReleaseStringUTFChars(buildVersion,version);
// we are called from JNI_OnLoad,so got to release LocalRef to avoid leaking
env->DeleteLocalRef(buildVersion);
// Query available memory size from a non-static public function
// we need use an instance of JniHelper class to call JNI
jmethodID memFunc = env->GetMethodID(g_ctx.jniHelperClz,"getRuntimeMemorySize","()J");
if (!memFunc) {
//LOGE("Failed to retrieve getRuntimeMemorySize() methodID @ line %d",__LINE__);
SDL_Log("DEBUG Failed to retrieve memory size");
return;
}
jlong result = env->CallLongMethod(instance,memFunc);
//LOGI("Runtime free memory size: %" PRId64,result);
SDL_Log("DEBUG RUN TIME FREE MEMORY SIZE");
(void)result; // silence the compiler warning
}
此函数从未调用过,我不确定谁是调用者。 CPP
extern "C" JNIEXPORT void JNICALL InvokeFunction(JNIEnv *env,jobject instance) {
SDL_Log("JNI CALL START TICKET");
pthread_t threadInfo_;
pthread_attr_t threadAttr_;
pthread_attr_init(&threadAttr_);
pthread_attr_setdetachstate(&threadAttr_,PTHREAD_CREATE_DETACHED);
pthread_mutex_init(&g_ctx.lock,NULL);
jclass clz = env->GetObjectClass(instance);
g_ctx.mainActivityClz = (jclass)env->NewGlobalRef(clz); // hack
g_ctx.mainActivityObj = env->NewGlobalRef(instance);
int result = pthread_create( &threadInfo_,&threadAttr_,UpdateTicks,&g_ctx);
assert(result == 0);
pthread_attr_destroy(&threadAttr_);
(void)result;
}
updateticks CPP //从未真正调用过此代码。
void* UpdateTicks(void* context) {
SDL_Log("DEBUG -- UPDATE TICKS IS CALLED");
TickContext *pctx = (TickContext*) context;
JavaVM *javaVM = pctx->javaVM;
JNIEnv *env;
jint res = javaVM->GetEnv((void**)&env,JNI_VERSION_1_6);
if (res != JNI_OK) {
res = javaVM->AttachCurrentThread(&env,NULL);
if (JNI_OK != res) {
//LOGE("Failed to AttachCurrentThread,ErrorCode = %d",res);
SDL_Log("FAILED TO ATTACH THREAD");
return NULL;
}
}
jmethodID statusId = env->GetMethodID(pctx->jniHelperClz,"updateStatus","(Ljava/lang/String;)V");
//sendJavaMsg(env,pctx->jniHelperObj,statusId,"TickerThread status: initializing...");
// get mainActivity updateTimer function
jmethodID timerId = env->GetMethodID(pctx->mainActivityClz,"updateTimer","()V");
struct timeval beginTime,curTime,usedTime,leftTime;
const struct timeval kOneSecond = {
(__kernel_time_t)1,(__kernel_suseconds_t) 0
};
//sendJavaMsg(env,"TickerThread status: start ticking ...");
while(1) {
gettimeofday(&beginTime,NULL);
pthread_mutex_lock(&pctx->lock);
int done = pctx->done;
if (pctx->done) {
pctx->done = 0;
}
pthread_mutex_unlock(&pctx->lock);
if (done) {
break;
}
env->CallVoidMethod(pctx->mainActivityObj,timerId);
gettimeofday(&curTime,NULL);
timersub(&curTime,&beginTime,&usedTime);
timersub(&kOneSecond,&usedTime,&leftTime);
struct timespec sleepTime;
sleepTime.tv_sec = leftTime.tv_sec;
sleepTime.tv_nsec = leftTime.tv_usec * 1000;
if (sleepTime.tv_sec <= 1) {
nanosleep(&sleepTime,NULL);
} else {
//sendJavaMsg(env,"TickerThread error: processing too long!");
}
}
//sendJavaMsg(env,"TickerThread status: ticking stopped");
javaVM->DetachCurrentThread();
return context;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。