C ++和Java进程之间的共享内存 [英] Shared memory between C++ and Java processes
问题描述
我的目标是将数据从C ++进程传递到Java进程,然后将结果接收回来.
My aim is to pass data from a C++ process to a Java process and then to receive a result back.
我已经通过命名管道实现了这一点,但是我希望共享数据而不是传递或复制数据,前提是访问会更快.
I have achieved this via a named pipe but I would prefer to share the data rather than passing or copying it, assuming the access would be faster.
最初,我想过要创建一个可以用Java读写的C ++共享段,但是我不确定是否可以通过JNI做到这一点,更不用说安全了.
Initially, I thought of creating a shared segment in C++ that I could write to and read with Java, but I'm not sure if this is possible via JNI, let alone safe.
我相信在Java中可以使用ByteBuffer.allocateDirect分配内存,然后使用GetDirectBufferAddress来访问C ++中的地址,但是如果我正确的话,这是针对JNI中的本机调用,而我无法在该地址中获取该地址.我的C ++程序?
I believe it's possible in Java to allocate the memory using ByteBuffer.allocateDirect and then use GetDirectBufferAddress to access the address in C++, but if I'm correct this is for native calls within JNI and I can't get this address in my C++ process?
迷失了.
非常感谢.
推荐答案
如果您拥有共享内存,例如使用 CreateFileMapping
(Windows)或shmget
(Unix),您所需要的只是Java方面的本机方法.然后,您可以创建 ByteBuffer
直接使用 NewDirectByteBuffer
像这样:
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;
现在,您必须获得一个指向共享内存的指针.在Windows上,您将使用以下内容:
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
现在,您只需创建一个由该共享内存支持的ByteBuffer
:
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);
}
这篇关于C ++和Java进程之间的共享内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!