Conversion between Java objects and native pointers
Maurizio Cimadamore
maurizio.cimadamore at oracle.com
Fri Dec 2 12:33:42 UTC 2022
To make sure I understand your use case (admittedly I'm not an expert in
ObjC). You want to define an ObjC class whose methods end up invoking
some piece of Java code? Would that be a fair description?
In general, "Java objects" cannot be converted into native pointers.
But, you can turn Java methods (method handles, to be precise) into
native pointers, and pass those to the ObjC class implementation. Would
that be enough?
Maurizio
On 02/12/2022 11:20, Gregory Klyushnikov wrote:
> I'm trying to use the preview Panama API to build an FFI for Objective C, allowing Java to fully interoperate with native macOS libraries. Calling out to existing classes is simple: you just use objc_msgSend and sel_registerName a bunch with the right arguments. But many macOS APIs want you to create your own classes and override methods (NSApplicationDelegate is one example and you seemingly can't do GUI without creating one) — which isn't as easy to do in a non-ugly way with the current Panama API.
>
> You *can* define a new Objective C class at runtime using objc_registerClassPair, but you don't have a good way of linking an ObjC object to its corresponding Java object. You can, obviously, store the pointer to the ObjC object in the Java object, but you can't do it the other way around, which poses a problem for overridden methods. The obvious solution to receiving calls to overridden methods would be:
> 1. Set their implementations as pointers to static methods
> 2. Create an instance variable in the ObjC object that would hold the pointer to its corresponding Java object
> 3. When a method is called, you'd get your Java `this` from that instance variable and forward the call to your Java object
>
> But I can't seem to find any way whatsoever, at least one that doesn't feel extremely hacky and thus unreliable, to convert a Java object to a native pointer and back. This would also be useful, in some circumstances, for those C APIs that take a function pointer and `void*` as the "context" and then pass that `void*` back to your function. Or are there better solutions that don't need this?
More information about the panama-dev
mailing list