如何传递java函数指针到c ++本地代码 [英] How to pass java function pointer to c++ native code

查看:213
本文介绍了如何传递java函数指针到c ++本地代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从java(android)代码调用本地c ++方法,并传递一个java函数作为参数,所以我将能够保存的函数指针在c ++代码,并从本机代码激活它。



我选择在java中使用匿名类实现函数指针,我从java调用native函数如下:

  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 ++?

解决方案

您可以编写一个C ++接口和SWIG它作为导演类。然后可以在Java中实现接口。在Java中实例化实现对象,并将其传递给一个C ++方法,该方法接受指针或对接口的引用,C ++将能够调用回您的Java类。例如:

  // 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 ;
}
}

文档:使用导演的跨语言多态性


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.

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

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++?

解决方案

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

And then:

// Java
public class MyFunction implements IStringToBool {
    public bool call(String s) {
        // do something
        return true;
    }
}

Documentation: Cross language polymorphism using directors

这篇关于如何传递java函数指针到c ++本地代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆