繁体   English   中英

从 java 调用原生 function 指针?

[英]call a native 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.

那么如何从MemoryAddress获取NativeSymbol呢? 或者是否有其他可能从 java 代码调用 function 指针。

我目前的解决方法是只使用 C 包装函数,如下所示:

void call_function(void (*func)(void)) {
    func();
}

然后调用这些函数

    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();

就像Johannes Kuhn评论的那样: NativeSymbol.ofAddress正是我所需要的。

所以代码看起来像这样:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM