关于 C 双指针参数的 JNA 问题求助, 例子很简单,求大佬指点下

2020-07-14 23:54:05 +08:00
 camork

话不多说,直接上代码:

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 函数, 但是获取结果出错了, 也不太清楚具体获取的步骤对不对, 有没有大佬指点下.

1485 次点击
所在节点    Java
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/690089

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX