Skip to content

Commit f710d62

Browse files
committed
feat: Describe ID factory approach in README
1 parent 6cca551 commit f710d62

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

README.md

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,54 @@ If a box2d method returns a pointer, it will not be registered for GC.
3636
> [!NOTE]
3737
> For more information on the bindings see the [documentation](https://github.com/libgdx/gdx-jnigen/blob/master/RUNTIME.MD#the-runtime).
3838
39+
### Working with VoidPointer context or user data
40+
Box2d supports passing a `void*` context to callbacks or attaching user data to a type.
41+
In java interop, we usually want this to be a java object. In a thread-safe manner, this can be achieved like this:
42+
```java
43+
public class Box2DIDFactory<T> {
44+
45+
private long id = 0;
46+
private LongMap<T> map = new LongMap<>();
47+
48+
public VoidPointer putData(T obj) {
49+
synchronized (this) {
50+
id += 1;
51+
map.put(id, obj);
52+
return new VoidPointer(id, false);
53+
}
54+
}
55+
56+
public void putData(T obj, VoidPointer pointer) {
57+
synchronized (this) {
58+
id += 1;
59+
map.put(id, obj);
60+
pointer.setPointer(id);
61+
}
62+
}
63+
64+
public long putDataRaw(T obj) {
65+
synchronized (this) {
66+
id += 1;
67+
map.put(id, obj);
68+
return id;
69+
}
70+
}
71+
72+
public T obtainData(VoidPointer pointer) {
73+
synchronized (this) {
74+
return map.get(pointer.getPointer());
75+
}
76+
}
77+
78+
public T obtainDataRaw(long pointer) {
79+
synchronized (this) {
80+
return map.get(pointer);
81+
}
82+
}
83+
}
84+
```
85+
86+
This is a very barebones example. It assumes you would want a factory per type. It is also designed thread-safe, which is not necessary.
3987

4088
## Java 8
4189
The project needs java 8 language features to build. However, it doesn't use any java 8 APIs and is therefor still safe to use with mobiVM.

0 commit comments

Comments
 (0)