从 C/C++ 在内存中写入缓冲区并在没有 JNI 的情况下用 java 读取它
我有一个问题,这可能吗?如何实现?从使用 Java 从 C/C++ 创建的内存缓冲区中读取字节?我的想法是使用 JNI 在 C++ 中启动一个循环,在缓冲区中写入字节,仅将缓冲区的方向发送到 Java,然后 Java 在另一个循环中从中读取字节。目标是减少 JNI 函数的调用,因为我注意到它们会降低性能。我想知道在 Java 中必须使用哪些类以及在 C++ 中必须使用哪些函数。
预先非常感谢
I have a question, is this possible and how? Reading bytes from a buffer in the memory that has been created from C/C++ with Java? My idea is to use JNI for starting a cycle in C++ that writes bytes in a buffer and only send the direction of the buffer to Java, then Java reads the bytes from it in another cycle. The goal is to reduce the call of JNI functions, because I noticed that they reduce the performance. I want to know which classes I must use in Java and what functions in C++.
In advance thank you very much
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 ByteBuffer。最简单的方法是使用
ByteBuffer.allocateDirect()
使用 Java 分配的地址。如果您必须使用 C 提供的地址,您可以更改地址和限制(大小)以指向您喜欢的任何位置。如果您想使用更底层的东西,在 Oracle JVM 上您可以使用
Unsafe.getXxxx(long address)
或Unsafe.setXxxx(long address, T value)
方法,但必须小心使用,因为不正确的使用可能会使 JVM 崩溃。 (就像在 C 中使用无效指针一样)这些方法由 ByteBuffer 使用,并转换为经过优化的单个机器代码指令。You can use a ByteBuffer. The simplest approach is to use a
ByteBuffer.allocateDirect()
using the address allocated by Java. If you have to use the address provided by C, you can change the address and limit (for the size) to point to anywhere you like.If you would rather use something more low level, on the Oracle JVM you can use the
Unsafe.getXxxx(long address)
orUnsafe.setXxxx(long address, T value)
methods, but these must be used with care as incorrect usage can crash the JVM. (Just like using an invalid pointer would in C) These methods are used by ByteBuffer and are turned into a single machine code instruction which optimised.