JNA可用内存在共享对象dll中创建

时间:2016-10-20 13:47:29

标签: java c++ eclipse jna

我试过libvirt java绑定并且当库试图使用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也是64位(1.8.0_101),Eclipse Neon Release 64Bit,JNA版本4.2.2。

程序在Native.free行停止,并提示App崩溃对话框,信息如下:

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中创建的释放内存是否错误?你能给我一些建议,谢谢!

1 个答案:

答案 0 :(得分:0)

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上运行而没有任何崩溃。