Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
StringToCharStarStar
#!/usr/bin/java --source 17 --enable-native-access ALL-UNNAMED --add-modules jdk.incubator.foreign
import jdk.incubator.foreign.*;
import java.util.*;
import java.util.stream.*;
public class StringToCharStarStar {
public static void main(String[] args) {
List<String> strings = List.of(args);
var scope = ResourceScope.newConfinedScope();
var allocator = SegmentAllocator.ofScope(scope);
var argv = allocator.allocateArray(CLinker.C_POINTER,
Stream.concat(strings.stream().map(s -> CLinker.toCString(s, scope)),
Stream.of(MemoryAddress.NULL)).toArray(Addressable[]::new));
var argc = IntStream.range(0, Integer.MAX_VALUE)
.filter(i -> MemoryAccess.getAddressAtIndex(argv, i) == MemoryAddress.NULL)
.findFirst().getAsInt();
var result1 = IntStream.range(0, argc)
.mapToObj(i -> CLinker.toJavaString(MemoryAccess.getAddressAtIndex(argv, i)))
.toList(); // ==> [a, b, c]
var result2 = MemoryAccess.getAddressAtIndex(argv, argc) == MemoryAddress.NULL; // ==> true
System.out.println(result1 + ", " + result2);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment