Cant write to shared memory. java.lang.Error: Invalid memory access Error

Cant write to shared memory. java.lang.Error: Invalid memory access Error

我正在尝试使用 JNA 创建共享内存并写入它。我真的很感激任何帮助。

这是我的代码:

import com.sun.jna.Memory;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.Kernel32;
import static com.sun.jna.platform.win32.WinBase.INVALID_HANDLE_VALUE;
import com.sun.jna.platform.win32.WinNT;
import static com.sun.jna.platform.win32.WinNT.PAGE_READWRITE;
import com.sun.jna.win32.W32APIOptions;

public class SharedMemoryTest
{
    private final MyKernel32 myKernel32;
    private Pointer SharedMemoryData;   
    private WinNT.HANDLE SharedMemoryHandle;

    public interface MyKernel32 extends Kernel32
    {
        MyKernel32 INSTANCE = (MyKernel32) Native.load("kernel32", MyKernel32.class, W32APIOptions.DEFAULT_OPTIONS);
    }

    public SharedMemoryTest()
    {
        myKernel32 = MyKernel32.INSTANCE;
    }

    public void test()
    {
        String SharedMemoryName = "SomeSharedMemory";
        int SharedMemorySize = 128;

        SharedMemoryHandle = myKernel32.CreateFileMapping((WinNT.HANDLE) INVALID_HANDLE_VALUE, null, PAGE_READWRITE, 0, SharedMemorySize, SharedMemoryName);

        if (SharedMemoryHandle == null) return;

        SharedMemoryData = myKernel32.MapViewOfFile(SharedMemoryHandle,
            PAGE_READWRITE,
            0, 0,
            SharedMemorySize);

        if (SharedMemoryData == null) return;

        System.out.println(SharedMemoryData.getByte(0));

        SharedMemoryData.setByte(0, (byte) 2);
    }
}

所以,当我 运行 test() 时,一切似乎都很好,直到我尝试使用 SharedMemoryData.setByte(0, (byte) 2); 写入内存的最后一行。这是我得到的错误:

java.lang.Error: Invalid memory access  
at com.sun.jna.Native.setByte(Native Method)
at com.sun.jna.Pointer.setByte(Pointer.java:993)

有谁知道问题出在哪里,或者有关于如何像这样设置共享内存的示例吗?

好的,问题不是关于 jna,而是关于 WinAPI。
参数 PAGE_READWRITE 不是 MapViewOfFile 的有效参数,请检查此 link:
https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-mapviewoffile
有效参数是 FILE_MAP_ALL_ACCESS、FILE_MAP_READ 或其他以 FILE_ 开头的参数。查看 link 了解更多详细信息。
参数 PAGE_READWRITE 相反是 CreateFileMapping 的有效参数。