jni 回调java函数接口,使用Interface在JNI中实现回调函数

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

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));

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;

}

解决方案

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.

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.

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;

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);

}

And the wrapper function is thus:

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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值