Memory Mapped file in C++ read in Java

2.2k views Asked by At

I have a C++ program that uses at one point

hMapFile = OpenFileMapping(dwDesiredAccess, bInheritHandle, lpName);

The lpName is something like "myfile" without extensions or path, i.e. a memory mapped file. I can find the file with the WinObj-Browser (WinObj) in the path Sessions\1\BaseNamedObjects\myfile. If I try to read that particular file in Java, I tried

File file = new File("myfile");
FileChannel filechannel = new RandomAccessFile(file, "r").getChannel();
MappedByteBuffer buffer = filechannel.map(FileChannel.MapMode.READ_ONLY, 0, filechannel.size());

But I get always the same error: Cannot find the specified file at the RandomAccessFile command. Maybe another file-access is needed? Which one?

As I understand by other posts, they always use a path and an extension, however, I have no idea that the path and extension would be in my case...

What I'm looking for, I a way to access the Kernel object namespacesKernel object namespaces

I know, there is this JNI example (Memorymap using JNI), however I would like to keep it simple and use nio (if even possible).

UPDATE

So I just tried the whole thing in C# and it was ridiculously easy, didn't take me more than 5 lines of code.

2

There are 2 answers

10
Daniel On

You need to use CreateFileMapping instead of OpenFileMapping. That way you will create an actual file on the disk which is associated with the file mapping.

Note: It is important to notice that using regular Read/Write methods will NOT be synchronized with a file mapping of a different process. So you still need to use something like MappedByteBuffer in Java

1
kaifong On

A file is a file, I agree with "Joachim Pileborg" that the Java program has not got the file in its working directory. Try

String working dir = System.getProperty("user.dir");

and make sure the file is in the correct path.