使用 JDK 16 中的 FFI 预览,我有这样的内存布局:
class FfiTest {
static GroupLayout layout = MemoryLayout.ofStruct(
C_INT.withName("someInt"),
MemoryLayout.ofPaddingBits(32), // So the following pointer is aligned at 64 bits
C_POINTER.withName("somePtr")
);
}
然后,我在本机代码的回调中收到指向此类结构的指针:
public static void someCallback(MemoryAddress address) {
try (MemorySegment seg = address.asSegmentRestricted(FfiTest.layout.byteSize())) {
// Works: fetching int from native structure, correct value is returned
VarHandle intHandle = FfiTest.layout.varHandle(int.class, MemoryLayout.PathElement.groupElement("someInt"));
int intResult = (int) vh.get(seg);
// Does not work: get the pointer as a MemoryAddress, fatal JVM crash with Hotspot log
VarHandle badPtrHandle = FfiTest.layout.varHandle(MemoryAddress.class, MemoryLayout.PathElement.groupElement("somePtr"));
// Works: get the pointer as a long, correct value is returned
VarHandle goodPtrHandle = FfiTest.layout.varHandle(long.class, MemoryLayout.PathElement.groupElement("somePtr"));
long longResult = (long) goodPtrHandle.get(seg);
}
}
在 JDK 代码中引发异常jdk.internal.foreign.Utils
:
public static void checkPrimitiveCarrierCompat(Class<?> carrier, MemoryLayout layout) {
checkLayoutType(layout, ValueLayout.class);
if (!isValidPrimitiveCarrier(carrier))
throw new IllegalArgumentException("Unsupported carrier: " + carrier); // Throws this exception, carrier has the value MemoryAddress
if (Wrapper.forPrimitiveType(carrier).bitWidth() != layout.bitSize())
throw new IllegalArgumentException("Carrier size mismatch: " + carrier + " != " + layout);
}
根据巴拿马文档, a 的 Java 载体C_POINTER
应该是MemoryAddress
,但这在这里不起作用。
那么使用 long 来访问此类指针是否正确?或者是其他东西?