【问题标题】:How to make a JNI for a Java Interface?如何为 Java 接口制作 JNI?
【发布时间】:2017-09-14 18:00:41
【问题描述】:

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

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

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

我试图为
JFoo.h:

创建一个 JNI
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方法,Java有一个特殊的native关键字。
  • 您是否考虑过查阅文档?而不是猜测?
  • 我知道native 关键字并且正在使用它(只是我的问题中没有包含完整的代码),谢谢!你能帮我指出正确的文档吗?我进行了很多搜索,但是鉴于 JNI 代表 Java Native Interface,因此很难专门缩小范围以创建 Java 接口的 JNI。 :( 我成功地创建了一个 Java 类的 JNI,但你是对的,我只是在猜测接口而不是类。
  • 检查jni tag wiki
  • 你应该开始here,然后阅读javah的工具文档和JNI规范。

标签: java c++ interface java-native-interface


【解决方案1】:

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

语言文档表明nativeclass declaration 中方法的允许修饰符,但不适用于interface declaration。编译器还会告诉您不能将native 放在哪里。

【讨论】:

    【解决方案2】:

    嗯,这样不行:(

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

    看这里:

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

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

    【讨论】:

    • .oOo。我喜欢早上投票的味道(没有解释);).oOo。
    猜你喜欢
    • 2020-03-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多