Modeling C-Strings with MemoryLayout?

Maurizio Cimadamore maurizio.cimadamore at oracle.com
Wed Dec 28 13:40:06 UTC 2022


Hi Gavin,
while something like that is possible, that would not be the best way to 
use memory layouts. I believe the sweet spot for memory layout is to 
capture data types whose size can be determined statically. 
Variable-length data structures don't fall in this case (another 
relatively common case is C struct which end with a variable-length 
array). While it would be possible, with some heroics, to enhance var 
handles to take extra dynamic access coordinates at runtimes, the 
condition under which this would be possible are very limited.

Perhaps it would be better to understand what you are trying to achieve 
by modelling a C string with a memory layout? Often, passing strings as 
opaque pointer just works. Note also that the FFM API provides some 
helper functions to allocate and dereference NULL terminated strings - 
see MemorySegment::get/setUtf8String, as well as 
SegmentAllocator::allocateUtf8String.

Cheers
Maurizio



On 25/12/2022 19:24, Gavin Ray wrote:
> Is it possible to model C-Strings with MemoryLayouts?
>
> I was thinking of using "MemoryLayout.sequenceLayout(0, C_CHAR)" and 
> computing the
> length at runtime, plus manually adding the null-terminator.
>
> Would this work alright, or is there some better way to do this?


More information about the panama-dev mailing list