【发布时间】:2020-07-14 15:20:17
【问题描述】:
JNA 遇到了关于指针指针问题的问题。
示例结构:
typedef struct _A {
unsigned int num;
struct _A *next;
} A, *PA;
C方法:
void test(PA *a) {
PA current = (PA) malloc(sizeof(A));
current->num = 123321;
PA next = (PA) malloc(sizeof(A));
next->num = 456;
current->next = next;
*a = current;
}
一个简单的C语言测试:
int main() {
PA a = NULL;
test(&a);
printf("%d\n", a->num);
printf("%d", a->next->num);
}
JNA 代码
public interface DLLLibrary extends Library {
......
void test(PointerByReference a);
}
public class A extends Structure {
public int num;
public ByReference next;
public A() {
super();
}
protected List<String> getFieldOrder() {
return Arrays.asList("num", "next");
}
public A(Pointer peer) {
super(peer);
}
public static class ByReference extends A implements Structure.ByReference { }
public static class ByValue extends A implements Structure.ByValue { }
}
最后,我试图获取在 C 中更新的结构字段,但得到“无效的内存访问”
public static void main(String[] args) {
PointerByReference pointer = new PointerByReference();
DLLLibrary.INSTANCE.test(pointer);
assert pointer.getValue().getInt(0) == 123321; //this works
A a = new A(pointer.getValue());
//assert a.next.num == 456; //excepted action
a.read(); //java.lang.Error: Invalid memory access
}
我的步骤有什么错误吗?
【问题讨论】: