我在jna中遇到一个非常简单的例子。我想用C语言在C语言中读取和写入结构。我在c:
中编译了一个非常简单的例子typedef struct {
int x;
} MyStruct;
我使用JNA在java中创建了相应的类:
import java.util.List;
import com.sun.jna.Pointer;
import com.sun.jna.Structure;
public class MyStruct extends Structure {
public int x;
public MyStruct(Pointer p) {
super(p);
}
@Override
protected List<String> getFieldOrder() {
return List.of("x");
}
}
我创建了一个测试结构的程序:
public class JnaJava {
public static void main(String[] args) {
NativeLibrary lib = NativeLibrary.getInstance(new File("libJnaC.so").getAbsolutePath());
MyStruct struct = new MyStruct(lib.getGlobalVariableAddress("myStruct"));
for (int i = 0; i < 2000000000; i++) {
struct.writeField("x", i);
System.out.println("val: " + struct.readField("x") + " it: " + i);
}
}
}
但我在400.000次迭代中遇到错误:
...
val:448536 it:448536
# A fatal error has been detected by the Java Runtime Environment:
# SIGSEGV (0xb) at pc=0x00007fb3d89e537b, pid=14464, tid=14466
# JRE version: Java(TM) SE Runtime Environment (10.0+46) (build 10+46)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (10+46, mixed mode, tiered, compressed oops, g1 gc, linux-amd64)
# Problematic frame:
# C [jna8855397332554224295.tmp+0x837b] Java_com_sun_jna_Native_setInt+0xab
# No core dump will be written. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
# An error report file with more information is saved as:
# /home/X/workspace/JnaJava/hs_err_pid14464.log
# If you would like to submit a bug report, please visit:
# http://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
有人能告诉我我的错误在哪里吗?这听起来像一个奇怪的记忆错误,但我不知道为什么?
提前致谢
马克
答案 0 :(得分:0)
这只是一个愚蠢的GC问题。将变量放入强引用中解决了问题。
https://groups.google.com/forum/#!topic/jna-users/4g3fLVi8Gxw