Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CLinker.toCString replacement in Java 18

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.

like image 720
czerny Avatar asked Oct 17 '25 07:10

czerny


1 Answers

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.

like image 76
Johannes Kuhn Avatar answered Oct 19 '25 20:10

Johannes Kuhn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!