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.
I use this snippet to convert strings to UTF-16:
private static MemoryAddress string(String s, ResourceScope scope) {
if (s == null) {
return MemoryAddress.NULL;
}
byte[] data = s.getBytes(StandardCharsets.UTF_16LE);
MemorySegment seg = MemorySegment.allocateNative(data.length + 2, scope);
seg.copyFrom(MemorySegment.ofArray(data));
return seg.address();
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With