我可以将 JNA 与 JNI 混合使用吗
我有一个自定义 dll,可以使用 JNA 从 Java 访问它。到目前为止一切都很完美。然而现在我想从我的 C 代码创建 Java 类。我认为这不能用 JNA 来完成,所以我所做的是创建一个 JNI 方法,但这导致我出现 UnsatisfiedLinkError。所以我的问题是:访问同一个 DLL 时可以混合使用 JNA 和 JNI 吗?如果可以,我应该如何做?
I have a custom dll that I access from Java using JNA. So far all is working perfect. Now however I would like to create Java classes from my C code. I assume this can't be done with JNA so what I did is to create a JNI method but this leads me to UnsatisfiedLinkError's. So my question is: Can I mix JNA and JNI when accessing the same DLL and if so, how should I go about doing that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当然,您可以混合访问 DLL,因为无论如何它只加载一次。问题在于链接到应用程序的工作方式:
JNA:
使用 JNA 时,您调用 jna 库的本机函数,该函数通过某种反射绑定到 DLL 中的函数。这样做的优点是您不必担心 DLL 中函数的名称,它们不必满足任何约定。
JNI:
简单的工作原理是从 Java 类到 DLL 中所需的方法名称的映射。如果您有一个包含具有以下签名的函数
int doStuff(int i, long john)
的类com.company.SomeClass
:如果缺少此函数,您将收到 UnsatisfiedLinkException 。
解决方案:
由于您似乎已经编写了自己的DLL,因此只需添加所需的函数作为包装函数即可。要获取函数签名,您可以使用 javah 命令自动创建头文件。
我建议阅读 Java 2 平台高级编程 - 第 5 章:JNI 技术< /a>.
Of course can you mix access to the DLL, since it is only loaded once anyway. The problem is how the linking to your application works:
JNA:
When using JNA you call the native functions of the jna library, which by some kind of reflection bind to the functions in your DLL. This has the advantage that you don't have to worry about the name of the functions in the DLL, they don't have to meet any conventions.
JNI:
Simple works by a mapping from your java classes to method names which are expected in the DLL. If you have a Class
com.company.SomeClass
containing a functionint doStuff(int i, long john)
with this signature:If this function is missing, you get the UnsatisfiedLinkException.
Solution:
Since it seems you have written your own DLL, just add the functions required as wrapper functions, and you are done. To get the function signatures, you can create a header file automatically with the
javah
command.I recommend reading Advanced Programming for the Java 2 Platform - Chapter 5: JNI Technology.
我想添加一件事来做到这一点。不要忘记每个 JNIEXPORT 的 extern "C" 以及 JNA 的函数。
举个简单的例子:
I want to add one thing to do that. Don't forget extern "C" for each JNIEXPORT and also function for JNA.
As a simple example: