<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  </head>
  <body>
    <p><br>
    </p>
    <div class="moz-cite-prefix">On 15/06/2023 17:18, Johannes Kuhn
      wrote:<br>
    </div>
    <blockquote type="cite" cite="mid:cafde073-83f1-00bd-c8d6-3cd1a58a0e0a@j-kuhn.de">Yes, I
      have read the thread. That StackOverflow question (and the thread)
      was just an other trigger to discuss a IMHO a more fundamental
      primitive: Passing an java object through a void* pointer.
      <br>
    </blockquote>
    <br>
    <br>
    <p>If you can create a JNI reference from an object and get a
      segment for it, you can also pass it to a foreign function, no?</p>
    <p>It seems to me that you want to be able to pass the object
      _directly_ to the function, which, to me, seems like a lot of
      accidental complexity for the linker machinery, with not a lot of
      upside (if you have some _other_ way to go Object -> segment).</p>
    <blockquote type="cite" cite="mid:cafde073-83f1-00bd-c8d6-3cd1a58a0e0a@j-kuhn.de">
      <br>
      <br>
      I just want a pair of methods that turn an object into a pointer
      and back - preferably with a deterministic "deallocation".
      <br>
      How that is implemented is a different story.
      <br>
    </blockquote>
    <p>In the thread I quoted, there's this:</p>
    <p>
      <blockquote type="cite">
        <pre>native long makeGlobalRef(Object o) // call NewGlobalRef, cast result to 
jlong and return
native void destroyGlobalRef(long ref) // cast to jobject, then call 
DeleteGlobalRef</pre>
      </blockquote>
      Wouldn't that pair of functions allow you to do what you want? It
      is fairly simple to provide FFM bindings for these. For instance,
      few weeks ago I created this class (note, JNIUtils define the
      native methods to bind to the functionality described above):</p>
    <p>```java<br>
      import java.lang.foreign.Arena;<br>
      import java.lang.foreign.MemorySegment;<br>
      <br>
      public class JNIUtilsWrapper {<br>
          public static MemorySegment newGlobalRef(Object o, Arena
      arena) {<br>
              return MemorySegment.ofAddress(JNIUtils.makeGlobalRef(o))<br>
                      .reinterpret(arena, (ref) ->
      JNIUtils.destroyGlobalRef(ref.address()));<br>
          }<br>
      <br>
          public static Object getRef(MemorySegment ref) {<br>
              return JNIUtils.readGlobalRef(ref.address());<br>
          }<br>
      }<br>
      ```</p>
    <p>Which I then used like so:<br>
      <br>
      ```java<br>
      try (Arena arena = Arena.ofConfined()) {<br>
            MemorySegment str = JNIUtilsWrapper.newGlobalRef("hello",
      arena);<br>
            System.out.println(JNIUtilsWrapper.getRef(str));<br>
      }<br>
      ```</p>
    <p>Maurizio<br>
    </p>
  </body>
</html>