且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从Java访问C ++共享库:JNI,JNA,CNI或SWIG?

更新时间:2023-12-03 23:23:34

JNA是最简单的使用,但正如你所说,需要手写一个C接口到C ++ API。它也可以比JNI慢一个数量级。但是,我在一台计算机上测量了几百纳秒的单个调用,因此除非在瓶颈中,否则不太可能影响。

JNA is the easiest to use, but as you note, requires hand-writing a C interface to the C++ API. It can also be slower than JNI by an order of magnitude. However, I measured individual calls at a few hundred nanoseconds on one machine, so that's unlikely to matter except in a bottleneck.

JNA在Java中冗余地指定C函数签名。 JNI可以在C字符串中冗余地指定Java函数签名。

JNA redundantly specifies C function signatures, in Java. JNI can redundantly specify Java function signatures, in C strings. Discrepancies in either can result in unexpected runtime behavior.

我个人会使用JNA,除非接口是复杂的,使得手写的C接口繁琐你,或者个人电话超过几百纳秒。

I personally would use JNA unless the interface is complex enough to make hand-writing the C interface cumbersome for you, or the individual calls are more than a few hundred nano seconds.

本周我遇到过这样的异常 - 一个丰富的C ++界面,有许多类和方法。我开始玩SWIG,看起来很有前途。它是相当容易使用,并自动生成Java绑定和C实现。智能指针确实需要一些额外的工作 - 你必须指示SWIG实例化模板。

This week I've been faced with such an exception -- a rich C++ interface with many classes and methods. I've started playing with SWIG, and it's looking promising. It's been fairly easy to use, and automatically generates the Java bindings and C implementation. Smart pointers did take a little extra work -- you have to instruct SWIG to instantiate the templates.

EDIT(一年后)

SWIG非常强大。它也可以更复杂的设置。对于简单,薄的接口,我可能会考虑JNA或JNI第一。但是SWIG对于厚接口是方便的。

SWIG is amazingly powerful. It can also be more complex to set up. For simple, thin interfaces, I'd probably consider JNA or JNI first. But SWIG is handy for thick interfaces.

由于一些C ++头文件的复杂性,我对SWIG的工作感到有点惊讶。但是SWIG似乎没有什么困难。

I'm a little surprised that SWIG works, given the complexity of some C++ header files. But SWIG appears to have little difficulty.

我必须写一些SWIG类型和包含C ++ / JNI代码的宏。例如,通过引用传递std :: strings需要自定义类型。将抛出的C ++异常转换为抛出的Java异常需要一个typemap和一个宏。

I did have to write some SWIG typemaps and macros containing C++/JNI code. For example, passing std::strings by reference required a custom typemap. Transforming thrown C++ exceptions to thrown Java exceptions required a typemap and a macro.

除了之外,我们的头文件不需要更改SWIG完全实例化了智能指针模板,该模板已被一些类不满足其对默认构造函数的期望。解决方案:添加一些默认构造函数。

No changes were needed to our header files except that SWIG fully instantiated a smart-pointer template, which had been parameterized with some classes that did not satisfy its expectation of a default constructor. Solution: add a few default constructors.