java共享内存,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.

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.

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?

Lost.

Many thanks in advance.

解决方案

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);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值