// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodType;

import jdk.incubator.foreign.CLinker;
import jdk.incubator.foreign.FunctionDescriptor;
import jdk.incubator.foreign.MemoryAddress;
import jdk.incubator.foreign.MemorySegment;
import jdk.incubator.foreign.ResourceScope;
import jdk.incubator.foreign.SymbolLookup;
import jdk.incubator.foreign.ValueLayout;

public class C18 {
    public static void main(String[] args) throws Throwable {
        System.loadLibrary("dyn");
        SymbolLookup sym = SymbolLookup.loaderLookup();
        CLinker linker = CLinker.systemCLinker();
        MethodHandle add = linker.downcallHandle(sym.lookup("add").get(),
                                                 FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.JAVA_INT, ValueLayout.JAVA_INT));
        MethodHandle dup = linker.downcallHandle(sym.lookup("dup").get(),
                                                 FunctionDescriptor.of(ValueLayout.ADDRESS, ValueLayout.ADDRESS));
        int a = 123;
        int b = 456;
        int c = (int)add.invoke(a, b);
        System.out.println(c);
        String s = "ABC";
        MemorySegment itmp = MemorySegment.allocateNative(4, ResourceScope.newSharedScope());  
        itmp.setUtf8String(0, s);
        MemoryAddress tmp = (MemoryAddress)dup.invoke(itmp);
        MemorySegment otmp = MemorySegment.ofAddress(tmp, 7, ResourceScope.newSharedScope()); 
        String s2 = otmp.getUtf8String(0);
        System.out.println(s2);
    }
}
