Shared memory between C++ and Java processes

不想你离开。 提交于 2019-11-28 06:28:46

If you have shared memory, for example using CreateFileMapping (Windows) or shmget (Unix), all you need is a native method on the Java side. Then you can create a ByteBuffer that directly accesses the shared memory using NewDirectByteBuffer like this:

JNIEXPORT jobject JNICALL Java_getSharedBuffer(JNIEnv* env, jobject caller) {
    void* myBuffer;
    int bufferLength;

Now you have to get a pointer to the shared memory. On Windows you would use something like this:

    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

Now you can just create a ByteBuffer that is backed by this shared memory:

    // put it into a ByteBuffer so the java code can use it
    return env->NewDirectByteBuffer(myBuffer, bufferLength);
}

Have you considered using 0MQ it supports both Java and C++ and will be more reliable. I think if you want to do shared memory in Java it would have to be via JNI, last time I looked there was not other way to do it.

This shows you have to do it via JNI if you go that route. Although the solutions I have found are Windows specific which may not apply to you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!