【发布时间】:2017-09-14 18:00:41
【问题描述】:
如何为 Java 接口创建 JNI,以便可以从 C++ 代码中的接口调用函数?
具体来说,我有一个Java接口
public interface Foo {
public void Bar(int a);
}
我试图为
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方法,Java有一个特殊的
native关键字。 -
您是否考虑过查阅文档?而不是猜测?
-
我知道
native关键字并且正在使用它(只是我的问题中没有包含完整的代码),谢谢!你能帮我指出正确的文档吗?我进行了很多搜索,但是鉴于 JNI 代表 Java Native Interface,因此很难专门缩小范围以创建 Java 接口的 JNI。 :( 我成功地创建了一个 Java 类的 JNI,但你是对的,我只是在猜测接口而不是类。 -
检查jni tag wiki。
-
你应该开始here,然后阅读
javah的工具文档和JNI规范。
标签: java c++ interface java-native-interface