Java object as a void*

Manuel Bleichenbacher manuel.bleichenbacher at gmail.com
Tue Feb 14 18:39:47 UTC 2023


Hi all

Many native SDKs allow the caller to pass a void* or long as an additional
parameter. This parameter is then later provided as a reference to the
original call, either in the context of a callback function call or as an
attribute of an operating system object. The native SDK will not interpret
the parameter in any way, neither as a number nor as a pointer. It's up to
the caller to know what it represents.

Examples are:

lParam in Windows' SendMessage() -
https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-sendmessage

dwNewLong in Windows' SetClassLongPtr() -
https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setclasslongptrw

arg in POSIX's pthread_create() -
https://pubs.opengroup.org/onlinepubs/000095399/functions/pthread_create.html

refcon in macOS' WritePipeAsync() -
https://developer.apple.com/documentation/iokit/iousbinterfaceinterface800/1639539-writepipeasync

Is there a way to use this from Java for Java objects, i.e. to pass a Java
object as a void* and later convert the void* back to the Java object?

Since the FFM API exposes void* as MemorySegments, it would probably mean
that a MemorySegment could be created encapsulating a reference to a Java
object, and that the Java object can later be retrieved from this
MemorySegment.

I am aware of two workarounds:

- In the context of a callback function, the Java callback function can be
extended with an additional parameter and then the Java object can be bound
to it. This function is then used to create the up call stub. Since the
callback function already contains the reference, the void* parameter is no
longer needed and can be passed MemorySegment.NULL. In my context (I/O
processing with several thousand functions calls per second), it likely is
rather inefficient as several thousand upcall stubs will need to be
generated by second.

- Instead of the Java object, a generated integer key could be passed as
the void*. The link between the key and the Java object would need to be
managed in a hash map. Possible, but more of a workaround.

Regards
Manuel
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/panama-dev/attachments/20230214/cf85d169/attachment.htm>


More information about the panama-dev mailing list