Skip to content

Commit

Permalink
Add note about function pointer lifetime and ObjectReferenceManager
Browse files Browse the repository at this point in the history
  • Loading branch information
praj-foss committed Dec 4, 2021
1 parent 773ee60 commit deefbd4
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion docs/TypeMappings.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,10 +130,24 @@ public interface ExampleLibrary {
}
int setCallback(MyCallback callback);
}
```

Any `MyCallback` instance can be passed as a function pointer now. This pointer is valid as long as the instance stays
strongly-referenced. So if you want to use the callback multiple times, it is advised to keep it referenced using an
`ObjectReferenceManager` like this:

```java
ObjectReferenceManager referenceManager = Runtime.getRuntime(lib).newObjectReferenceManager();
MyCallback callback = data -> 0;
Pointer key = referenceManager.add(callback);

lib.setCallback(callback); // Callback is passed internally as a function pointer

referenceManager.remove(key); // Free the callback when no more required
```


# Global Variables

Global variables are uncommon in C libraries however JNR-FFI still supports them.
Expand Down

0 comments on commit deefbd4

Please sign in to comment.