如果你有共享内存,例如使用CreateFileMapping
(Windows)或(Unix),你所需要的只是在Java端有一个本机方法。然后,您可以创建一个字节缓冲器,该字节缓冲器
使用NewDirectByteBuffer
直接访问共享内存,如下所示:shmget
JNIEXPORT jobject JNICALL Java_getSharedBuffer(JNIEnv* env, jobject caller) {
void* myBuffer;
int bufferLength;
现在,您必须获取指向共享内存的指针。在Windows上,你会使用这样的东西:
bufferLength = 1024; // assuming your buffer is 1024 bytes big
HANDLE mem = OpenFileMapping(FILE_MAP_READ, // assuming you only want to read
false, "MyBuffer"); // assuming your file mapping is called "MyBuffer"
myBuffer = MapViewOfFile(mem, FILE_MAP_READ, 0, 0, 0);
// don't forget to do UnmapViewOfFile when you're finished
现在,您可以创建一个由此共享内存支持的内存:ByteBuffer
// put it into a ByteBuffer so the java code can use it
return env->NewDirectByteBuffer(myBuffer, bufferLength);
}