使用ffi,是否可以将指向dart函数的指针传递到C模块(即* .so库)中,并直接从* .so库访问此dart函数并通过回调使用它?
int myPlus(int a, int b) {
print("dart.myPlus.a=$a,b=$b. $a+$b => ${a + b}");
return a + b;
}
main() {
...
ffi.Pointer<ffi.NativeFunction<NativeIntptrBinOp>>
pointer = ffi.Pointer.fromFunction(myPlus, 0);
print(pointer);
ffi.Pointer<ffi.NativeFunction<NativeApplyTo42And74Type>>
p17 = dylib.lookup("ApplyTo42And74");
ApplyTo42And74Type applyTo42And74 = p17.asFunction();
int result = applyTo42And74(pointer);
print("result => $result");
}
c:
#include <stdio.h>
#include <stdint.h>
typedef intptr_t (*IntptrBinOp)(intptr_t a, intptr_t b);
intptr_t ApplyTo42And74(IntptrBinOp binop) {
printf("ApplyTo42And74()\n");
intptr_t retval = binop(42, 74);
printf("returning %lu\n", retval);
return retval;
}
结果:
Pointer<NativeFunction<(IntPtr, IntPtr) => IntPtr>>: address=0x7fb4acd98000
ApplyTo42And74()
dart.myPlus.a=42,b=74. 42+74 => 116
returning 116
result => 116