--- /dev/null
+package de.unixwork.ui;
+
+import java.lang.foreign.Arena;
+import java.lang.foreign.MemorySegment;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+
+import static java.lang.foreign.Arena.global;
+
+public class CUtils {
+ public static MemorySegment cstring(String s) {
+ if(s == null) {
+ return MemorySegment.NULL;
+ }
+ ToolkitFuncs tk = ToolkitFuncs.getInstance();
+
+ byte[] utf8 = s.getBytes(StandardCharsets.UTF_8);
+ try {
+ long size = utf8.length + 1;
+ MemorySegment cstr = (MemorySegment) tk.malloc.invoke(size);
+ MemorySegment segment = MemorySegment.ofAddress(cstr.address());
+ ByteBuffer buf = segment.asByteBuffer();
+ buf.put(utf8);
+ buf.put((byte) 0);
+ return cstr;
+ } catch (Throwable e) {
+ throw new RuntimeException(e);
+ }
+ }
+}
public MethodHandle text_set;
public MethodHandle text_get;
+ // some libc stuff
+ public MethodHandle malloc;
+ public MethodHandle free;
+
private ToolkitFuncs(Linker linker, SymbolLookup lib) {
// void* func(void*)
FunctionDescriptor sigm_m = FunctionDescriptor.of(ValueLayout.ADDRESS, ValueLayout.ADDRESS);
FunctionDescriptor sigm_mm = FunctionDescriptor.of(ValueLayout.ADDRESS, ValueLayout.ADDRESS);
FunctionDescriptor sigv_mm = FunctionDescriptor.ofVoid(ValueLayout.ADDRESS, ValueLayout.ADDRESS);
FunctionDescriptor sigv_m = FunctionDescriptor.ofVoid(ValueLayout.ADDRESS);
+ FunctionDescriptor sigm_l = FunctionDescriptor.of(ValueLayout.ADDRESS, ValueLayout.JAVA_LONG);
MemorySegment object_get_context_addr = lib.find("ui_object_get_context").orElseThrow();
MemorySegment text_set_addr = lib.find("ui_text_set").orElseThrow();
MemorySegment text_get_addr = lib.find("ui_text_get").orElseThrow();
+ MemorySegment malloc_addr = lib.find("malloc").orElseThrow();
+ MemorySegment free_addr = lib.find("free").orElseThrow();
+
object_get_context = linker.downcallHandle(object_get_context_addr, sigm_m);
// use JAVA_LONG for size_t, because we don't support 32bit platforms
double_get = linker.downcallHandle(double_get_addr, FunctionDescriptor.of(ValueLayout.JAVA_DOUBLE, ValueLayout.ADDRESS));
text_set = linker.downcallHandle(text_set_addr, sigv_mm);
text_get = linker.downcallHandle(text_get_addr, sigm_m);
+
+ malloc = linker.downcallHandle(malloc_addr, sigm_l);
+ free = linker.downcallHandle(free_addr, sigv_m);
}
static ToolkitFuncs getInstance() {