Arena.addCloseAction and the implementation of a custom allocator
Maurizio Cimadamore
maurizio.cimadamore at oracle.com
Sat Mar 4 14:59:38 UTC 2023
Hi,
you can still do that, using MemorySegment::ofAddress:
|public MemorySegment allocate(long byteSize, long byteAlignment) { if
(byteAlignment > MAX_ALIGNMENT) { throw new IllegalArgumentException();
} try { var arena = Arena.ofAuto(); long address =
(long)MALLOC.invokeExact(byteSize); // I assume this should work since
other reinterpret casts like unsigned <-> int is legal here return
MemorySegment.ofAddresss(address, byteSize, arena, () -> { try {
FREE.invokeExact(address); } catch(Throwable e) { throw new
RuntimeException(e); } }); } catch(Throwable e) { throw new
RuntimeException(e); } } |
That is, there is a new overload in |MemorySegment::ofAddress| that does
exactly what you want.
I hope this helps.
Cheers
Maurizio
On 04/03/2023 10:10, Quân Anh Mai wrote:
> Hi,
>
> I noticed that the method Arena::addCloseAction has been dropped from
> the API. May I ask in that case what is the way to create a
> custom allocator that manages its allocated memory? With the method, I
> believe it can be achieved with something like this:
>
> public MemorySegment allocate(long byteSize, long byteAlignment) {
> if (byteAlignment > MAX_ALIGNMENT) {
> throw new IllegalArgumentException();
> }
>
> try {
> var arena = Arena.ofAuto();
> long address = (long)MALLOC.invokeExact(byteSize); // I assume
> this should work since other reinterpret casts like unsigned <-> int
> is legal here
> arena.addCloseAction(() -> {
> try {
> FREE.invokeExact(address);
> } catch(Throwable e) {
> throw new RuntimeException(e);
> }
> });
> return MemorySegment.ofAddress(address, byteSize, arena);
> } catch(Throwable e) {
> throw new RuntimeException(e);
> }
> }
>
> Thanks a lot,
> Quan Anh
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/panama-dev/attachments/20230304/00dfa953/attachment-0001.htm>
More information about the panama-dev
mailing list