-1

我想在 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

4

1 回答 1

1

您的代码对我来说几乎是正确的。您只需要保留分配的段(代表heif_image_handle**),然后在调用之后,在库将主图像句柄设置到其中之后从该段中heif_context_get_primary_image_handle检索(使用 JDK 17 API 的示例):MemoryAddress

// 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);

通常,像在 C 中那样进行堆栈分配并获取已分配值的地址,如您显示的代码段中所示,在 Java 中是不可能的。因此,就巴拿马外国 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路线。由于无法获取 a 的地址MemoryAddress

通常,Java API 没有与&& 运算符等效的功能。该.address()方法用于将类似地址的事物转换为MemoryAddress实例,而不是模仿&。而MemoryAddress它本身只是返回this(所以你的primary_image_handle.address()电话没有效果)。

本质上,在没有堆栈分配的情况下,我们在 Java 中所做的 C 等价物&是这样的:

some_type** val_ptr = malloc(sizeof *val_ptr);
func(val_ptr); // void func(some_type** v) { ... }
some_type* val = *val_ptr;
于 2022-01-23T14:51:45.760 回答