您的代码对我来说几乎是正确的。您只需要保留分配的段(代表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;