Java 16, as part of incubating package jdk.incubator.foreign, used to provide convenient way to convert Java Strings 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.
I use this snippet to convert strings to UTF-16:
Note that the tailing null character takes 2 bytes in UTF-16 - if you use a different encoding, you may need to modify the string before (
s + '\000').UTF-16 is good enough for my purposes - calling the Windows API.