我编写了 JNI 包装器来导出嵌入 JVM 的 C 应用程序 (G-WAN) 的 API。 native 调用在 C 应用程序中实现并使用 RegisterNatives() 导出。
理想情况下,我会为 G-WAN API 提供一个“gwan”类:
import gwan // G-WAN API
public class hello {
public static int jmain(long env, String[] args) {
gwan.xbuf_cat(gwan.get_reply(env), "Hello World");
return 200; // HTTP status (200:'OK')
}
}
我想做类似上面“#import gwan”的操作来导入 native 调用原型(prototype),但目前我只有以下(有效):
public class hello {
public static int jmain(long env, String[] args) {
gwan_xbuf_cat(gwan_get_reply(env), "Hello World");
return 200; // HTTP status (200:'OK')
}
public static native long gwan_get_reply(long env);
public static native void gwan_xbuf_cat(long ctx, String str);
}
同样, native 调用的实现是在 G-WAN 可执行文件中进行的(而不是在存储在磁盘上的 Java 类中)。
因为 the G-WAN API is quite large ,如果可能的话,我希望在它们自己的“gwan”类(或命名空间)中使用 native 调用原型(prototype)(如上面的第一个 hello 示例)。
关于如何做到这一点有什么建议吗? (请贴出 Java 或 JNI 代码,因为我不是 Java 专家)
免责声明:我参与了这个项目的开发。
最佳答案
我建议您阅读以下来自 Sun now Oracle 的关于 JNI 的论文
http://java.sun.com/docs/books/jni/html/jniTOC.html
在那之后它应该是可以理解的,但是一些伪代码和它未经测试的是将两个 gwanapi 调用移动到它自己的名为 gwanapi.java 的文件中
public class gwanapi {
public static native long get_reply(long answer);
public static native void xbuf_cat(long ctx,String str);
}
然后你用 javac gwanapi.java
编译那个文件 -> 输出:gwanapi.class
您为 c/c++ header 实现键入 javah -jni:
javah -jni gwanapi
接下来你应该在你的 hello java 类中调用 static{ System.loadLibrary("gwanapi");}
伪代码,未经测试
public class hello{
static{
System.loadLibrary("gwanapi");
}
public static int jmain(long env,String args[]){
gwanapi.xbuf_cat(gwanapi.get_reply(env),"Hello World!");
return 200;
}
}
你应该可以开始了。
但我可能漏掉了一两点,但我认为这是您应该做的最少工作量。
哦对了http://en.wikipedia.org/wiki/Java_Native_Interface也是 JNI 调用及其工作原理的某种形式的源代码,并引导您访问更多站点和更多信息。
谢谢
关于java - JNI native 调用 *prototypes* 在他们自己的类/ namespace ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9339287/