如果您有共享内存,例如使用CreateFileMapping
(Windows) 或shmget
(Unix),您所需要的只是 Java 端的本机方法。然后您可以创建一个ByteBuffer
直接访问共享内存的方法,NewDirectByteBuffer
如下所示:
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);
}