2023-01-19 314
假设一个包含类的Java库,我们称其为Foo.该类包含一个构造函数和两种方法:
// constructor
Foo();
// returns a random int
public int bar();
// generates a random int "x" and calls integerGenerated(x)
public void generateInt(IntGeneratorListenerInterface listenerInterface);
这是使用一种方法的Java接口IntGeneratorListenerInterface:
void integerGenerated(int generatedInt);
我可以从本机C和C ++打电话bar().这是一个C ++示例,假设适当初始化的JNIEnv env:
// instantiate Foo
jclass fooClass = env->FindClass("com/my/package/Foo");
jmethodID constructorMethodID = env->GetMethodID(fooClass, "<init>", "()V");
jobject fooInstance = env->NewObject(fooClass, constructorMethodID);
// call bar()
jmethodID barMethodID = env->GetMethodID(fooClass, "bar", "()I");
jint result = env->CallIntMethod(fooInstance, barMethodID);
printf("%d", result);
我想做的是从c/c ++实现接口IntGeneratorInterface,以便当我使用类似的jni调用调用generateInt()时,我可以在C中接收回调,例如:
void integerGenerated(int x)
{
// do something with the int
}
我的问题:是否有任何方法可以在C/C ++中实现Java接口,以便我可以将有效的东西传递给generateInt(),并且在C?
我已经研究了JNI的RegisterNatives(),但我相信这需要Java代码声明并调用”本机”方法(如果我错了,请纠正我),而且我没有修改的奢侈品现有的Java库.另请注意,琐碎的Java库仅在这里用来举例说明我的问题.我意识到这样的简单功能可以很容易地本地编写.
是.就像您使用任何其他本机方法一样:
class NativeRunnable implements Runnable {
@Override
public native void run();
}
现在只使用javah创建标头文件并实现函数.
以上所述是小编给大家介绍的是否可以使用JNI在C或C ++中实现Java接口?,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对77isp云服务器技术网的支持!
原文链接:https://77isp.com/post/25909.html
=========================================
https://77isp.com/ 为 “云服务器技术网” 唯一官方服务平台,请勿相信其他任何渠道。
数据库技术 2022-03-28
网站技术 2022-11-26
网站技术 2023-01-07
网站技术 2022-11-17
Windows相关 2022-02-23
网站技术 2023-01-14
Windows相关 2022-02-16
Windows相关 2022-02-16
Linux相关 2022-02-27
数据库技术 2022-02-20
抠敌 2023年10月23日
嚼餐 2023年10月23日
男忌 2023年10月22日
瓮仆 2023年10月22日
簿偌 2023年10月22日
扫码二维码
获取最新动态