Dart/Flutter ffi (Foreig Function Interface) native callbacks eg: sqlite3_exec

后端 未结 1 858
面向向阳花
面向向阳花 2021-01-16 01:23

Hello I am using dart:ffi to build an interface with my native c/c++ library. and I needed a way to get a callback from c to dart as an example in sqlite:

in         


        
相关标签:
1条回答
  • 2021-01-16 01:44

    I got an example to work. Hopefully you can adapt this to your case.

    Example C function

    EXTERNC int32_t foo(
                        int32_t bar,
                        int32_t (*callback)(void*, int32_t)
                        ) {
        return callback(nullptr, bar);
    }
    

    Dart code

    First the typedefs. We need two for the native function foo and one for the Dart callback.

    typedef example_foo = Int32 Function(
        Int32 bar, Pointer<NativeFunction<example_callback>>);
    typedef ExampleFoo = int Function(
        int bar, Pointer<NativeFunction<example_callback>>);
    
    typedef example_callback = Int32 Function(Pointer<Void>, Int32);
    

    and the code for the callback

      static int callback(Pointer<Void> ptr, int i) {
        print('in callback i=$i');
        return i + 1;
      }
    

    and the lookup

      ExampleFoo nativeFoo =
        nativeLib.lookup<NativeFunction<example_foo>>('foo').asFunction();
    

    and, finally, use it like this:

      int foo(int i) {
        return nativeFoo(
          i,
          Pointer.fromFunction<example_callback>(callback, except),
        );
      }
    

    as expected, foo(123) prints flutter: in callback i=123 and returns 124

    0 讨论(0)
提交回复
热议问题