简体   繁体   English

有没有一种方法可以使用JNI从Java调用C ++的STL库?

[英]Is there a way to call the STL Libraries of C++ from Java using JNI?

有没有一种方法可以从JNI调用STL库,我相信JNI为本地调用提供了一个类似于C的接口,我们如何为C ++模板库实现此功能?

I agree that if you're looking for just the plain STL, you could probably use a Java library instead. 我同意,如果您只是在寻找普通的STL,则可以改用Java库。 However, if you insist on wrapping STL, SWIG provides some STL wrapping in JNI out of the box (see this for the basic mechanism), which should produce relatively stable, tested code. 但是,如果你坚持包裹STL,SWIG提供了JNI一些STL包装开箱(见的基本机制),这应该产生相对稳定的,经过测试的代码。

Yes. 是。 You required to use the swig typemap to convert C++ STL classes to Java objects... and vice versa. 您需要使用Swig类型映射将C ++ STL类转换为Java对象...反之亦然。 For more information, please visit, http://www.swig.org/Doc2.0/Android.html 有关更多信息,请访问http://www.swig.org/Doc2.0/Android.html

I know this is possible, although I haven't done it myself. 我知道这是可能的,尽管我自己还没有做到。 But JNI code can crash the JVM if you are not VERY CAREFUL. 但是,如果您不太谨慎,JNI代码可能会使JVM崩溃。 Also, JNI code is much more difficult to maintain than Java code. 而且,JNI代码比Java代码难维护得多。 I was on one project where the Java -> JNI -> STL and COM code was thrown away and we replaced it with C# accessing the same STL and COM and a socket. 我在一个项目中,扔掉了Java-> JNI-> STL和COM代码,我们用C#替换了它,访问了相同的STL和COM和一个套接字。 We never looked back. 我们再也没有回头。

If you are doing only a small amount of JNI, it may be worth it. 如果你正在做的只是JNI 少量 ,它可能是值得的。 If you are creating a large interface via JNI, I strongly recommend instead writing the component that interacts with STL in C# instead of Java, and using a socket to communicate between the C# and Java components. 如果要通过JNI创建大型接口,则强烈建议改用C#而不是Java编写与STL交互的组件,并使用套接字在C#和Java组件之间进行通信。 It will be far easier to write, test, and maintain. 编写,测试和维护将容易得多

I have to ask why you find it necessary to use the STL libraries from Java. 我不得不问为什么您觉得有必要使用Java的STL库。 Is there something in them that's not provided by Java's own massive set of libraries? 它们中是否有Java自己的大量库无法提供的功能?

I understand why you'd have to call your own code (and I'm assuming you've profiled the Java code and found it wanting, otherwise your effort is wasted) but you seem to be asking how to call STL stuff directly. 我理解为什么您必须调用自己的代码(并且我假设您已经剖析了Java代码并发现了它的需要,否则浪费了您的精力),但是您似乎在询问如何直接调用STL东西。

We've often had trouble with JNI and it makes our code less portable, so you have to have a very good reason for wanting to use it in our shop, and you have to prove with hard data, why the Java-supplied stuff is not adequate. 我们经常曾与JNI的麻烦,这让我们的代码的可移植性,所以你必须有一个很好的理由为希望在我们的商店使用它,你必须有确凿的数据,为什么在Java提供的东西是证明不充分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM