使用Interface在JNI中实现回调函数 [英] Implement callback function in JNI using Interface

查看:1913
本文介绍了使用Interface在JNI中实现回调函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Java中使用interface实现回调函数。我写了应用程序部分为 MyJavaFunction(int size,m_GetSizeInterface);

I need to implement callback function in Java using "interface". I have wrote the application part as MyJavaFunction(int size, m_GetSizeInterface);

m_GetSizeInterface是一个接口,回调函数GetSize。这个GetSize方法是在应用程序中的覆盖。在JNI中,我需要调用具有原型 int MyCPPFunction(int size,int(* callback)(int * ID))的CPP函数;

m_GetSizeInterface is an Interface which contains the callback function GetSize. This GetSize method is override in the application. In JNI I need to call a CPP function having prototype int MyCPPFunction(int size, int (*callback)(int* ID));

如何将此GetSize作为参数传递给JNI中的MyCPPFunction?请帮助

How can I pass this GetSize as parameter to MyCPPFunction in JNI? Please help

public int GetSize (m_SizeClass arg0)
{
    g_size = arg0.size;
        return 0;
}


推荐答案

想要调用本地C ++代码,而你又要调用一个java方法。这实际上有点棘手。

The complication here is that you want to invoke native C++ code which you, in turn, want to invoke a java method. This is actually a bit tricky.

您需要创建一个用于java调用的JNI C ++函数,以及一个与
匹配的C ++函数MyCPPFunction回调签名。后者将作为一个包装器来调用java方法。

You need to create a JNI C++ function for java to call, and a C++ function matching the MyCPPFunction callback signature. The latter will act as a wrapper to call the java method.

因为包装器将需要关于JNI环境的信息,这不能由参数提供(为了破坏签名),你创建一些全局变量来保存它: / p>

Because the wrapper will need information about the JNI environment, which cannot be provided by parameters (lest we ruin the signature) you create a few global variables to hold it:

jobject g_getSizeIface;
jmethodID g_method;
JNIEnv *g_env;

java将调用的C ++函数如下:

The C++ function which java will call is the following:

JNIEXPORT void JNICALL Java_ClassName_MyCPPFunction
     (JNIEnv *env, jint size, jobject getSizeInterface)
{
      jclass objclass = env->GetObjectClass(getSizeInterface);
      jmethodID method = env->GetMethodID(objclass, "GetSize", "(m_SizeClass)I");
      if(methodID == 0){
          cout << "could not get method id!\n";
          return;
      }
      g_method = method;
      g_getSizeIface = getSizeInterface;
      g_env = env
      MyCPPFunction(size, WrapperFunc);
}

而且包装函数是:

int WrapperFunc(int *id)
{
      jint retval;
      //marshalling an int* to a m_SizeClass boogy-woogy.
      ...
      g_env->ExceptionClear();
      retval = g_env->CallIntMethod(g_getSizeIface, g_method, 
                                    /*marshalled m_SizeClass*/);
      if(g_env->ExceptionOccured()){
          //panic! Light fires! The British are coming!!!
          ...
          g_env->ExceptionClear();
      }     
      return rvalue;
}

这篇关于使用Interface在JNI中实现回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆