java-gi icon indicating copy to clipboard operation
java-gi copied to clipboard

Graal Native Image

Open jwharm opened this issue 5 months ago • 4 comments

Graal Native Image for JDK 24 has experimental support for the FFM API: https://www.graalvm.org/jdk24/reference-manual/native-image/native-code-interoperability/foreign-interface/ It would be nice if java-gi would support this. To make it work, the java-gi bindings generator must generate a GraalVM “ForeignRegistrationFeature” class that registers all downcall and upcall FunctionDescriptiors used in the module.

Notes:

  • Use command-line arguments -H:+UnlockExperimentalVMOptions and -H:+ForeignAPISupport
  • Upcalls in Native Image currently only work on Linux.
  • Custom GObject class registration uses reflection intensively, so that will probably not work.

jwharm avatar Jul 05 '25 13:07 jwharm

In my experience with my own libraries, most cases of reflection can also be covered by an annotation processor, which makes native image easier and means less magic, which I think is cleaner. At a minimum, an AP seems like a good fit for GtkTemplate (potentially in combination with a ServiceLoader if early discovery is needed)

JFronny avatar Jul 12 '25 16:07 JFronny

I'd love to replace the reflection code with an annotation processor 🙂 With early discovery, do you mean that it could be used to register Java classes as GTypes during startup? That would be really useful.

jwharm avatar Jul 13 '25 20:07 jwharm

Exactly. An annotation processor can output resource files, which includes the resource files used for the service loader mechanism. This is what AutoService is built on, for example. At runtime, a different component can then invoke the service loader to automatically discover the classes the annotation processor registered. You can even use the AP to generate a glue class that performs the actual registration and register that instead, which makes this more resilient by not relying on no-arg constructors in user code to generate instances.

JFronny avatar Jul 13 '25 20:07 JFronny

Yes the "glue class" would call GObjects.typeRegisterStaticSimple(), GObjects.typeAddInterfaceStatic() etc with the correct names, types and properties from the annotated class.

Using a ServiceLoader for this is really neat. I've been looking at Classgraph to scan the classpath for GObject-derived classes, but a ServiceLoader is just perfect for this.

jwharm avatar Jul 13 '25 20:07 jwharm