如何将java函数指针传递给c++本机代码

How to pass java function pointer to c++ native code(如何将java函数指针传递给c++本机代码)

本文介绍了如何将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++本机代码

基础教程推荐