通过JNI接口共享输出流 [英] Sharing output streams through a JNI interface

查看:137
本文介绍了通过JNI接口共享输出流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个通过JNI接口使用C ++库的Java应用程序。 C ++库创建类型为 Foo 的对象,这些对象通过JNI正式传递给Java。

I am writing a Java application that uses a C++ library through a JNI interface. The C++ library creates objects of type Foo, which are duly passed up through JNI to Java.

假设库有输出函数

    void Foo::print(std::ostream &os)

我有一个Java OutputStream out 。如何从Java调用 Foo :: print ,以便输出显示在 out ?有没有办法将 OutputStream 强制转换为JNI层中的 std :: ostream ?我可以在缓冲区中捕获JNI层的输出,然后将其复制到 out 吗?

and I have a Java OutputStream out. How can I invoke Foo::print from Java so that the output appears on out? Is there any way to coerce the OutputStream to a std::ostream in the JNI layer? Can I capture the output in a buffer the JNI layer and then copy it into out?

推荐答案

我会实现一个C ++ ostream来缓冲写入(最多一些设置大小),然后通过JNI将这些写入刷新到java OutputStream。

I would implement a C++ ostream that buffers writes (Up to some set size) before flushing those writes to a java OutputStream via JNI.

在java方面,您可以使用常规的OutputStream实例,也可以实现缓冲区块的排队(实际上是byte [])以避免任何可能的锁定争用线程之间。实际输出流仅由另一个线程上的任务使用,该线程从队列中提取块并将它们写入OutpuStream。我不能说在这个详细程度上是否有必要 - 你可能会发现直接写入JNI工作的输出流。

On the java side, you can either use a regular OutputStream instance, or you can implement queueing of the buffer blocks (essentially byte[]) to avoid any possible locking contention between threads. The real output stream is used only by a task on another thread that pulls blocks from the queue and writes them to the OutpuStream. I can't say if this is necessary or not at this level of detail - you may well find writing directly to the output stream from JNI works.

我不知道与JNI分享其他海报问题,并没有看到使用JNI的任何问题。当然,你的维护者必须知道他们的东西,但就是这样,Java / C ++层的复杂性可以通过文档,示例和测试用例来管理。在过去,我已经实现了一个具有相当繁琐的接口的Java<> COM桥 - 在性能,线程或维护方面没有问题。

I don't share the other posters concerns with JNI, and don't see any problem with using JNI for this. Sure, your maintainers will have to know their stuff, but that's about it, and the complexity of the Java/C++ layer can be managed with documentation, examples and test cases. In the past, I've implemented a Java<>COM bridge with quite a chatty interface - no problem with performance, threading or maintainance.

鉴于完全自由的选择,没有JNI,但对我来说,它通过使其他不兼容的系统紧密集成而节省了一天。

Given a totally free choice, there'd be no JNI, but for me, it has saved the day by making possible the tight integration of otherwise incompatible systems.

这篇关于通过JNI接口共享输出流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆