繁体   English   中英

如何为 Java 接口创建 JNI?

[英]How to make a JNI for a Java Interface?

如何为 Java 接口创建 JNI,以便我可以在 C++ 代码中从接口调用函数?

具体来说,我有一个Java接口

public interface Foo {
    public void Bar(int a);
}

我试图为它创建一个 JNI
JFoo.h:

class JFoo {
    ...
    public: 
        void Bar(int a);
    ...
};

JFoo.c:

...
void JFoo::Bar(int a) {
    //Not sure what to put here. If I don't have then I have issues because 
    "declaration of 'void JFoo::Bar(int)' outside of class is not 
    definition"
    return;
} 
...

所以从另一个 C++ 文件我可以做

JFoo foo123;
foo123 = ... //the Java object which implements the Foo interface is what actually passes in 'foo123'
foo123.bar(5); //This ideally executes the Java object's implementation of bar

我还尝试在 JFoo 中使用virtual void来代替抽象 C++ 类,但这不起作用,因为您“不能将字段 'foo123' 声明为抽象类型”。

如何为 Java 接口制作 JNI?

JNI 用于实现实例(没有static )或类( static )方法。 即使类包含其他抽象方法,方法实现也意味着具体方法。 接口的方法是完全抽象的。

语言文档表明native类声明中方法的允许修饰符,但不适用于接口声明 编译器还会告诉您不能放置native

好吧,它不是那样工作的:(

你不能这样走。 JNI 允许您通过 JNI 实现中提供的函数调用本机方法和操作 Java 对象。 但这与一对一映射无关。

看看这里:

https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo025

此示例展示了如何从 C++ 调用类的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM