【问题标题】:JNA free memory created in the shared object dll在共享对象 dll 中创建的 JNA 可用内存
【发布时间】:2017-03-02 13:33:09
【问题描述】:

我尝试了 libvirt java bindings,当库尝试使用 Native.free 方法释放 dll 中分配的内存时总是出现 Access Violation 错误,所以我编写了以下简单测试。

public class HelloWorld {

    public interface CLibrary extends Library {
        CLibrary INSTANCE = (CLibrary) Native.loadLibrary("msvcrt", CLibrary.class);

        Pointer _strdup(String src);
    }

    public static void main(String[] args) {
        Pointer p = CLibrary.INSTANCE._strdup("HelloWorld");
        Native.free(Pointer.nativeValue(p));
    }
}

我的环境如下: Windows 7 Ultimate SP1 64Bit, Jdk&Jvm 也是64bit(1.8.0_101), Eclipse Neon Release 64Bit, JNA version 4.2.2。

程序停在Native.free行,提示App crash dialog,信息如下:

Problem signature:
   Problem Event Name: APPCRASH
   Application name: javaw.exe
   Application version: 8.0.1010.13
   Application timestamp: 576a4c7e
   Fault module name: StackHash_c84f
   Faulty module version: 6.1.7601.18247
   Faulty module timestamp: 521eaf24
   Exception code: c0000374
   Exception offset: 00000000000c4102
   OS version: 6.1.7601.2.1.0.256.1
   Locale ID: 2052
   Additional Information 1: c84f
   Additional information 2: c84f3cec06e628f5bb4621d27c86f80d
   Additional Information 3: 3b2e
   Additional Information 4: 3b2e22e89759af30ea1b1d716fbf08f3

所以我想知道这种释放在 dll 中创建的内存的方法是否错误?能给我一些建议吗,谢谢!

【问题讨论】:

  • 您为什么不尝试将free 定义添加到您的界面并使用它?它可能无法解决您的崩溃问题,但您可以直接传递Pointer,而不是提取整数值用作参数。
  • 是的,我现在用这个方法来释放内存,但是不知道对不对,程序没有crash了。

标签: java c++ eclipse jna


【解决方案1】:
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Pointer;

public class MemoryTest {

    public interface CLibrary extends Library {
        CLibrary INSTANCE = (CLibrary) Native.loadLibrary("c", CLibrary.class);

        Pointer strdup(String src);
    }

    public static void main(String[] args) {
        Pointer p = CLibrary.INSTANCE.strdup("HelloWorld");
        Native.free(Pointer.nativeValue(p));
        System.gc();
    }

}

此测试确实在 Linux Ubuntu64 16.04 上运行,没有任何崩溃。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-06
    • 2011-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多