簡體   English   中英

如何通過 java 外國 memory api 傳遞值指針

[英]How to pass over a value pointer via java foreign memory api

我想在 C(定義在這里)中調用以下方法:

heif_image_handle* handle;
heif_context_get_primary_image_handle(ctx, &handle);

我遇到的問題是我無法通過 C-API 訪問 struct heif_image_handle 它被定義為沒有定義的結構

struct heif_image_handle;

我試過的:

try (var scope = ResourceScope.newSharedScope()) {
    MemoryAddress heif_context_alloc = heif_context_alloc();
    // ...
    MemoryAddress primary_image_handle = MemorySegment.allocateNative(C_POINTER, scope).address();
    heif_context_get_primary_image_handle(scope, primary_image_handle.address(), heif_context_alloc);
    // ...
}

有人可以幫助我如何將這種方法與巴拿馬 API 一起使用。 我的實際解決方法是擴展 C-API,但原作者不想這樣做。

我的實際代碼在: https://github.com/lanthale/LibHeifFX/blob/main/LibHeifFX/src/main/java/org/libheiffx/LibheifImage.java

您的代碼對我來說幾乎是正確的。 您只需要保留分配的段(表示heif_image_handle** ),然后在調用heif_context_get_primary_image_handle后,在庫將主圖像句柄設置到該段后從該段中檢索MemoryAddress (使用 JDK 17 API 的示例):

// allocate blob of memory the size of a pointer
MemorSegment primary_image_handle_seg = MemorySegment.allocateNative(C_POINTER);
// call library to set the handle into the allocated memory
heif_context_get_primary_image_handle(ctx, primary_image_handle_seg.address());
// retrieve pointer from allocated memory
MemoryAddress primary_image_handle = MemoryAccess.getAddress(primary_image_handle_seg);

通常,在 Java 中,無法直接在 Java 中進行堆棧分配並獲取分配值的地址,如 C 中的代碼段所示。 因此,就巴拿馬外國 API 而言,每當您在 C 代碼中看到這樣的內容時:

some_type* val;

您需要為其分配一個MemorySegment

// some_type** val_ptr;
MemorySegment val_ptr = MemerySegment.allocateNative(C_POINTER, scope);
// some_type** val_ptr_as_ma; (as a bare MemoryAddress)
MemoryAddress val_ptr_as_ma = val.address();
// some_type* val; (dereference/copy val, `*val_ptr`)
MemoryAddress val = MemoryAccess.getAddress(val);

請注意,在這種情況下,我們必須通過MemorySegment路由到 go。 因為不可能獲取MemoryAddress的地址。

通常,Java API 沒有&符運算符的等效項。 .address()方法用於將類似地址的東西轉換為MemoryAddress實例,而不是模仿& 而對於MemoryAddress本身,它只是返回this (所以你的primary_image_handle.address()調用沒有效果)。

本質上,C 相當於我們在 Java 中所做的,沒有堆棧分配和& ,是這樣的:

some_type** val_ptr = malloc(sizeof *val_ptr);
func(val_ptr); // void func(some_type** v) { ... }
some_type* val = *val_ptr;

暫無
暫無

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

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