Does anybody have a simple example on how to call a C function from Java 17 that includes creating a C library and how to setup a MethodHandle?
The JEP description at https://openjdk.java.net/jeps/412 does have an example, but I've been struggling to understand it.
I think it can be achieved using Project Panama (https://jdk.java.net/panama/) jextract, but since this feature was included in the JDK, I didn't want to use Panama.
I collated various of the code snippets I read from JEP412 / Panama into this simple example class, which demonstrates how to set up method handles in Java 17 for calling C runtime library and showing use of Java->C and C->Java calls.
It is not optimised in any way. Longer term using
jextract
is much better than handcoding the various method handles for up/downcalls from Java->C and C->Java, and it will hugely cut down on the effort to build Java API mappings for your own or other native library.The sample will run on JDK17 Windows 10 and GNU/Linux (I used OpenJDK 17), though for GNU/Linux you may need to adjust setting for library loads such as
-Djava.library.path=/lib/x86_64-linux-gnu
.Run the example with command:
Note the Foreign Memory API is in incubating stage, so APIs change frequently. With small extra effort this sample could be adjusted run on JDK16 or the latest build of JDK Panama Foreign. The C runtime calls are built-in but if you experiment with other libraries you would need to call
System.loadLibrary("xyz");
before symbol lookups fromxyz.dll
orlibxyz.so
.