【发布时间】:2021-06-15 18:36:26
【问题描述】:
我有固定数量的固定长度的字节数组 (byte[]) 我想存储在本机内存中(并稍后检索)。但是,我不太确定如何将多个数组直接存储在 MemorySegment 中。
我知道我可能会创建一个大型 MemorySegment 并逐个元素地对其进行初始化,但我认为这种策略会很慢并且会使检索更加麻烦(也许?)。
在 API 文档中,我遇到了 SegmentAllocator 抽象,这似乎解决了我的分配问题,但我不明白如何使用此 SegmentAllocator 检索分配的数据。
try(ResourceScope scope = ResourceScope.newConfinedScope()){
byte[] data = objToByteArray(someClass.getDeclaredConstructor().newInstance()); //suppose data is always of constant length
SegmentAllocator alloc = SegmentAllocator.arenaAllocator(numOfArrays* data.length, scope);
for(int i = 0; i < numOfArrays; i++){
alloc.allocateArray(MemoryLayouts.JAVA_BYTE, data);
data = objToByteArray(someClass.getDeclaredConstructor().newInstance());
}
//how can I access the arrays in alloc?
}catch(Exception e){
e.printStackTrace();
}
有没有办法访问 SegmentAllocator 中的数据,或者是否有其他方法可以解决我的问题?
【问题讨论】:
-
你似乎忽略了
allocateArray的返回值,它返回了包含数据的MemorySegment。
标签: java project-panama