话不多说,直接上代码:
C 结构体
typedef struct _A {
unsigned int num;
struct _A *next;
} A, *PA;
测试方法
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 { }
}
public static void main(String[] args) {
PointerByReference pointer = new PointerByReference();
DLLLibrary.INSTANCE.test(pointer);
assert pointer.getValue().getInt(0) == 123321; //这里是正确的
A a = new A(pointer.getValue());
//assert a.next.num == 456; //后续期望的调用
a.read(); //java.lang.Error: Invalid memory access
}
最后 Java 这边传个双重指针给 C 函数, 但是获取结果出错了, 也不太清楚具体获取的步骤对不对, 有没有大佬指点下.