JNA内存泄漏-如何解决? [英] JNA Memory Leak - How to fix?

查看:1033
本文介绍了JNA内存泄漏-如何解决?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

        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 ++,老实说,我不知道如何在此处实际释放内存:(

I haven't touched C/C++ since college and I honestly have no clue how to actually free the memory here :(

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

I know that there's a memory leak - I did some profiling with YourKit and traced a memory leak to this block of code (specifically, it seems to be leaking in the GetWindowTextW call and the Native.toString() calls). Could someone just give me an example of how to properly free up whatever memory blocks are being used?

我看到Pointer具有clear()方法,我应该使用该方法吗?但是我不知道如何获取大小(clear需要一个长度参数).我还看到有一个Memory类型可以将Pointer子类化,但是根据instanceof,我现在拥有的所有指针实际上都不是其实例.

I see that Pointer has a clear() method, should I use that? But I don't know how to get the size (clear takes a length argument). I also see that there's a Memory type that subclasses Pointer, but according to instanceof, none of the Pointers I have right now are actually instances of that.

推荐答案

使用 CloseHandle .请记住,OpenProcess返回一个Handle,而不是一个Pointer.

After opening a handle to a process with OpenProcess, you need to close the process handle with CloseHandle. Remember that OpenProcess returns a Handle, not a Pointer.

Kernel32.INSTANCE.CloseHandle(process);

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

Note also that JNA provides a pretty in-depth mapping of the Windows API out of the box in the net.java.dev.jna-platform package (I think?)

这篇关于JNA内存泄漏-如何解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆