JNA 内存泄漏 - 如何修复?

JNA Memory Leak - How to fix?

        public static User32 USER32_INSTANCE = (User32) Native.loadLibrary("user32", User32.class);

        user32 = USER32_INSTANCE;

        user32.EnumWindows((hWnd, arg) -> {
          int size = 1024 * 8;
          char[] buffer = new char[size];
          USER32_INSTANCE.GetWindowTextW(hWnd, buffer, size);

          char[] buffer2 = new char[size];
          PointerByReference pointer = new PointerByReference();
          User32DLL.GetWindowThreadProcessId(hWnd, pointer);
          Pointer process = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, pointer.getValue());
          Psapi.GetModuleBaseNameW(process, null, buffer2, size);

          String result = Native.toString(buffer).trim();
          String proc = Native.toString(buffer2).trim();

          // ... (non-JNA stuff)
        }

自大学以来我就没接触过 C/C++,老实说,我不知道如何真正释放这里的内存:(

我知道存在内存泄漏 - 我使用 YourKit 进行了一些分析,并追踪到此代码块的内存泄漏(具体来说,它似乎在 GetWindowTextW 调用和 Native.toString()调用)。有人能给我一个例子,说明如何正确释放正在使用的任何内存块吗?

我看到 Pointer 有一个 clear() 方法,我应该使用那个吗?但我不知道如何获得大小(clear 需要一个长度参数)。我还看到有一个 Memory 类型是 Pointer 的子类,但根据 instanceof,我现在拥有的指针 none 实际上是它的实例。

使用 OpenProcess, you need to close the process handle with CloseHandle 打开进程句柄后。请记住,OpenProcess returns 是 Handle,而不是 Pointer

Kernel32.INSTANCE.CloseHandle(process);

另请注意,JNA 在 net.java.dev.jna-platform 包中提供了开箱即用的 Windows API 的非常深入的映射(我认为?)