如何通过void指针从C向GraalVM Native Image Java入口传递字节数组?
问题原因
CTypeConversion.asByteBuffer创建的是直接ByteBuffer,这类缓冲区直接映射到本地内存,并没有关联的Java字节数组。而ByteBuffer.array()方法仅对基于Java数组的非直接缓冲区有效,直接缓冲区调用该方法就会抛出UnsupportedOperationException。
解决方案
你有两种可行的修复方式:
方式1:复制直接缓冲区内容到Java数组
创建一个byte数组,通过ByteBuffer的get()方法将缓冲区内容复制进去:
@CEntryPoint(name = "printStruct") public static void printStruct(IsolateThread thread, VoidPointer message, int size) { System.out.println(message.isNull()); ByteBuffer buf = CTypeConversion.asByteBuffer(message, size); // 创建数组并复制缓冲区内容 byte[] bytes = new byte[size]; buf.get(bytes); System.out.println(new String(bytes)); }
方式2:使用GraalVM工具类直接复制本地内存
利用CTypeConversion的copyBytes方法,直接将本地内存中的数据复制到Java数组:
@CEntryPoint(name = "printStruct") public static void printStruct(IsolateThread thread, VoidPointer message, int size) { System.out.println(message.isNull()); // 直接将本地内存复制到Java数组 byte[] bytes = CTypeConversion.copyBytes(message, size); System.out.println(new String(bytes)); }
补充说明
直接ByteBuffer是为了高效与本地内存交互设计的,避免了额外内存拷贝,但代价是无法直接获取底层Java数组。上述两种方法都能解决读取内容的需求,其中方式2是GraalVM提供的原生简洁方案。
内容的提问来源于stack exchange,提问作者egor10_4
相关产品推荐
相关产品推荐

