Skip to content

Instantly share code, notes, and snippets.

@shalupov
Last active May 7, 2022 15:45
Show Gist options
  • Save shalupov/31c53bbdff73a412662507ef19383973 to your computer and use it in GitHub Desktop.
Save shalupov/31c53bbdff73a412662507ef19383973 to your computer and use it in GitHub Desktop.
jna: typed "reference placeholders"
package com.sun.jna.platform.mac;
import com.sun.jna.Pointer;
import com.sun.jna.ptr.PointerByReference;
import java.util.function.Function;
class ByReference<T extends CoreFoundation.CFTypeRef> extends PointerByReference {
private final Function<Pointer, T> typedValueFactory;
public ByReference(Function<Pointer, T> typedValueFactory) {
this(typedValueFactory, null);
}
public ByReference(Function<Pointer, T> typedValueFactory, T initialValue) {
super(initialValue == null ? null : initialValue.getPointer());
this.typedValueFactory = typedValueFactory;
}
@Override
public void setValue(Pointer value) {
// type check
typedValueFactory.apply(value);
super.setValue(value);
}
public T getRefValue() {
Pointer value = super.getValue();
if (value == null) {
return null;
}
return typedValueFactory.apply(value);
}
}
class CFDictionaryRefPlaceholder extends ByReference<CoreFoundation.CFDictionaryRef> {
public CFDictionaryRefPlaceholder() {
this(null);
}
public CFDictionaryRefPlaceholder(CoreFoundation.CFDictionaryRef initialValue) {
super(CoreFoundation.CFDictionaryRef::new, initialValue);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment