Java 16, as part of incubating package jdk.incubator.foreign
, used to provide convenient way to convert Java String
s to C strings of arbitrary Charset using MemorySegment CLingker.toCString​(String str, Charset charset, NativeScope scope)
. That method was removed since Java 17. Is there currently a convenient method to convert Java String
to C string of selected Charset?
Java 18 has void MemorySegment.setUtf8String(long offset, String str)
. However that obviously only supports UTF8.
On JDK18 I use a conversion of
(s+"\0")
which typically adds 1, 2 or 4 bytes as null termination to the end of theMemorySegment
for the C string - depending on the character set used:Windows Java -> Wide string is then:
toCString(allocator, s, StandardCharsets.UTF_16LE)
Hopefully someone can offer a more efficient / robust way to convert. The above works for round-trip tests I've done on a small group of character sets (Windows + WSL), but I'm not confident it is reliable in all situations.