为了账号安全,请及时绑定邮箱和手机立即绑定

带有附加参数的 JNA 回调函数

带有附加参数的 JNA 回调函数

精慕HU 2021-09-03 17:10:38
我在让 JNA 全部解决时遇到问题。我正在尝试调用一个函数,该函数将函数和const char*. 我的 C 代码如下所示:typedef void (*example_ptr)(const char*);void exampleMethod(const char* value){    printf("This is the string: %s\n", value);}void example_triggerCallback(const example_ptr func, const char* str) {    printf("provided str: %s", str);    func(str);}为了实现这一点,我用 Java 编写了这样的 JNA 包装器public class Main {    public interface TestLibrary extends Library {        TestLibrary INSTANCE = (TestLibrary)                Native.loadLibrary("libtest",                        TestLibrary.class);        interface ExampleCallback extends Callback {            void invoke(String str);        }        class ExampleCallbackImpl implements ExampleCallback {            public void invoke(String str) {                System.out.println("example: " + str);            }        }        void example_triggerCallback(ExampleCallback callback, String str);    }    public static void main(String[] args) {        TestLibrary testLibrary = TestLibrary.INSTANCE;        final TestLibrary.ExampleCallbackImpl callback = new TestLibrary.ExampleCallbackImpl();        testLibrary.example_triggerCallback(callback, "testiddy test test");    }}我现在面临的问题是,printf在example_triggerCallbackC代码其实是在正打来电话,我得到的输出Java控制台上,但什么我真的想在这里实现的是,我想从Java传递侧指针为exampleMethod从C 所以它会打印通过的String. 现在func(str)好像被忽略了。我在这里缺少什么?
查看完整描述

1 回答

?
喵喔喔

TA贡献1735条经验 获得超5个赞

基于JNA 文档中的内容:


typedef void (*ExampleCallback)(const char*);


void exampleMethod(const char* value)

{

    printf("This is the string: %s\n", value);

}


void example_triggerCallback(const example_ptr func, const char* str) {

    printf("provided str: %s", str);

    func(str);

}

public interface CLibrary extends Library {

    // define an interface that wraps the callback code

    public interface ExampleCallbackInterface extends Callback {

        void invoke(String val);

    }


        // functions available in library (name must match)

    public void exampleMethod(String  value);

    public void example_triggerCallback(ExampleCallbackInterface callback);

}


// define an implementation of the callback interface

public static class CallbackExample implements Example22CallbackInterface {

    private CLibrary lib;


    public CallbackExample(CLibrary useLib) {

        lib = useLib;

    }


    @Override

    public void invoke(String val) {

        lib.exampleMethod(val);

    }

}


...

final CLibrary clib = (CLibrary)Native.loadLibrary("testlib", CLibrary.class);

...

// instantiate a callback wrapper instance

final CallbackExample callback = new CallbackExample(clib);


// pass the callback wrapper to the C library

clib.example_triggerCallback(callback);

由于我在其他互联网位置回答了这个问题,因此我知道它适用于提问者。


查看完整回答
反对 回复 2021-09-03
  • 1 回答
  • 0 关注
  • 310 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信