[英]call a native function pointer from java?
Is it possible to call a function pointer from Java?是否可以从 Java 调用 function 指针?
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. 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
?那么如何从
MemoryAddress
获取NativeSymbol
呢? Or is there an other possibility to call a function pointer from java code.或者是否有其他可能从 java 代码调用 function 指针。
My current workaround is to just use C wrapper functions, like this:我目前的解决方法是只使用 C 包装函数,如下所示:
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.就像Johannes Kuhn评论的那样: NativeSymbol.ofAddress正是我所需要的。
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.