【问题标题】:Not able to call a void java member function from the native function in android无法从android中的本机函数调用void java成员函数
【发布时间】:2011-07-29 14:54:46
【问题描述】:

我在 android-ndk 中遇到问题。当我尝试从 cpp 调用 java nan-static 成员函数时,我也没有收到任何运行时错误,但没有调用函数。
但是当我尝试从 cpp 调用 java 静态成员函数时,我能够成功调用,成员函数定义正在成功执行。

/********** For static member function */
/* This is the c code */ 

jmethodID method = env->GetStaticMethodID(interfaceClass, "callBack", "(Ljava/lang/String;)V");
if(!method) {
    LOGE("Callback_handler: Failed to get the callback method");
    return;
}
env->CallStaticVoidMethod(interfaceClass, method, js);

/* This is the function in the java */
    public static void callBack(String s) {
    Bundle b = new Bundle();
    b.putString("callback_string", s);
    Message m = Message.obtain();
    m.setData(b);
    //Sending to the handler
    h.sendMessage(m);
}

上面的代码运行良好,但下面的代码不起作用

/********** For member function */
/* This is the c code */ 
jmethodID method = env->GetMethodID(interfaceClass, "callBack", "(Ljava/lang/String;)V");
LOGE("callback_handler: method %d", method);
if(!method) {
    LOGE("Callback_handler: Failed to get the callback method");
    return;
}


/* Call the callback function */
env->CallVoidMethod(interfaceClass, method, js);

/* This is the function in the java */
    public void callBack(String s) {
    Bundle b = new Bundle();
    b.putString("callback_string", s);
    Message m = Message.obtain();
    m.setData(b);
    //Sending to the handler
    h.sendMessage(m);
}   

如果我遗漏了什么,请告诉我。

感谢和问候,
SSuman185

【问题讨论】:

  • 你缺少类的实例我假设interfaceClass 是类实例,而不是类的实例
  • 更准确地说... interfaceClass 是描述某些类型/类的对象...您需要创建此类型/类的对象并将其传递给 CallVoidMethod
  • 嗨 Selven,你的假设是正确的,interfaceClass 在类实例中,而不是类(对象)的实例,请告诉我如何获取对对象的引用。
  • 感谢 Selvin,它现在可以工作了。

标签: android callback android-ndk


【解决方案1】:

在调用成员函数时,不要使用类实例作为类参数。使用类的实例作为 cls 参数。那么我们也可以调用成员函数了。

Selvin 给出了答案,它工作正常,但他没有回答,而是添加了 cmets。所以,我正在更新答案。请把功劳归功于他。

感谢和问候,
SSuman185

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-14
    相关资源
    最近更新 更多