簡體   English   中英

JNA:從指向結構的指針中獲取值

[英]JNA : Get value from a pointer to a pointer to a structure

我在 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 中更新的結構字段,但得到“無效的 memory 訪問”

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
}

我的步驟有什么錯誤嗎?

當您收到“無效的 memory 訪問”錯誤時,您應該開始查看本地 memory 分配何時完成。 通常 API 會記錄(並告訴您如何釋放它),如果沒有,您知道這是您的責任。 在這種情況下,您可以在您發布的 C 代碼中看到,分配是在測試方法中完成的:

PA current = (PA) malloc(sizeof(A));

PA next = (PA) malloc(sizeof(A));

這里的問題是 Java 端不知道該分配,因此您必須手動進行。

您使用 PointerByReference 映射PointerByReference看起來不錯。 雖然您可以在返回時使用getInt(0) ,但此時您最好只從返回的指針中實例化A結構,就像您所做的那樣:

A a = new A(pointer.getValue());

那么a.num應該是您預期的 123321。然后您必須獲取返回的指針(指向本機分配的鏈接)並使用它來創建另一個 Java 端結構:

A b = new A(a.next);

(您可能只想在結構中使用Pointer來簡化該部分。如果您使用ByReferenceA.ByReference ,則在此部分使用getPointer() 。)

在這一點上,我相信b.num應該給你 456。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM