How to pass java function pointer to c++ native code(如何将java函数指针传递给c++本机代码)
问题描述
我想从 java (android) 代码中调用原生 c++ 方法,并将 java 函数作为参数传递,这样我就可以将函数指针保存在 c++ 代码中,并从原生代码中激活它.
I want to call a native c++ method from java (android) code, and pass a java function as a parameter, so I will be able to save the function pointer in the c++ code, and activate it from the native code.
我选择使用匿名类在java中实现函数指针,并从java中调用native函数如下:
I chose to implement the function pointer in java using anonymous class, and I call the native function from java as following:
interface FunctionPtrHelper {
bool function(String param);
}
NativeFunc(param1,param2,new FunctionPtrHelper() {
public bool myFunction(String param) {
//body of my function
}});
如何让 swig/jni 知道第三个参数(实际上是一个类)并将其转换为 c++ 中的函数指针(将包含'myFunction')?
如果不可能,是否有另一种方法可以将函数指针从 java 传递给 c++?
How can I make swig/jni know the 3rd param (which is actually a class) and translate it to a function pointer in c++ (that will contain'myFunction') ?
In case it is not possible, is there another way to pass a function pointer from java to c++?
推荐答案
您可以编写一个 C++ 接口并将其 SWIG 作为导演"类.然后你可以用Java实现接口.在 Java 中实例化实现对象并将其传递给 C++ 方法,该方法采用指向接口的指针或引用,C++ 将能够回调您的 Java 类.例如:
You can write a C++ interface and SWIG it as a "director" class. Then you can implement the interface in Java. Instantiate the implementation object in Java and pass it into a C++ method that takes a pointer or reference to the interface, and C++ will be able to call back into your Java class. For example:
// SWIGed C++
class IStringToBool
{
public:
virtual bool call(std::string s) = 0;
}
class IStringToBoolUser
{
public:
void setFunction(IStringToBool &function);
}
然后:
// Java
public class MyFunction implements IStringToBool {
public bool call(String s) {
// do something
return true;
}
}
文档:使用导向器的跨语言多态性
这篇关于如何将java函数指针传递给c++本机代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将java函数指针传递给c++本机代码


- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 获取数字的最后一位 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 转换 ldap 日期 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01