Is it possible to call a function pointer from Java?
To call a C function from Java I can just use the down call method from the CLinker
, but that works only for functions and not for function pointers, since it needs a NativeSymbol
for the function.
So how can I get a NativeSymbol
from a MemoryAddress
?
Or is there an other possibility to call a function pointer from java code.
My current workaround is to just use C wrapper functions, like this:
void call_function(void (*func)(void)) {
func();
}
and then just call these functions
CLinker link = CLinker.systemCLinker();
MethodHandle handle = link.downcallHandle(link.lookup("get_function_pointer").orElseThrow(), FunctionDescriptor.of(ADDRESS);
MemoryAddress funcPntr = (MemoryAddress) handle.invoke();
handle = link.downcallHandle(link.lookup("call_function").orElseThrow(), FunctionDescriptor.of(ADDRESS);
handle.invoke();
Like Johannes Kuhn commented: NativeSymbol.ofAddress is exactly what I need.
So the code looks like this:
CLinker link = CLinker.systemCLinker();
MethodHandle handle = link.downcallHandle(link.lookup("get_function_pointer").orElseThrow(), FunctionDescriptor.of(ADDRESS);
MemoryAddress funcPntr = (MemoryAddress) handle.invoke();
try (ResourceScope scope = ResourceScope.newConfinedScope()) {
NativeSymbol funcSymbol = NativeSymbol.ofAddress("symbol_name", funcPntr, scope);
MethodHandle handle = linker.downcallHandle(funcPntr, FunctionDescriptor.ofVoid());
handle.invoke();
}