简体   繁体   中英

write a buffer in memory from C/C++ and read from it in java without JNI

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

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) or Unsafe.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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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