FFI functions_callbacks
2020-12-30 本文已影响0人
CentForever
C++
typedef intptr_t (*IntptrBinOp)(intptr_t a, intptr_t b);
// Returns a closure.
// Note this closure is not properly marked as DART_EXPORT or extern "C".
// Used for testing passing a pointer to a closure to Dart.
// TODO(dacoharkes): is this a supported use case?
DART_EXPORT IntptrBinOp IntptrAdditionClosure() {
std::cout << "IntptrAdditionClosure()\n";
IntptrBinOp retval = [](intptr_t a, intptr_t b) { return a + b; };
std::cout << "returning " << &retval << "\n";
return retval;
}
Dart
typedef NativeIntptrBinOp = IntPtr Function(IntPtr, IntPtr);
typedef NativeIntptrBinOpLookup = Pointer<NativeFunction<NativeIntptrBinOp>>
Function();
调用
{
// Return a c pointer to a c function from a c function.
Pointer<NativeFunction<NativeIntptrBinOpLookup>> p14 =
ffiTestFunctions.lookup("IntptrAdditionClosure");
NativeIntptrBinOpLookup intptrAdditionClosure = p14.asFunction();
Pointer<NativeFunction<NativeIntptrBinOp>> intptrAdditionPointer =
intptrAdditionClosure();
BinaryOp intptrAddition = intptrAdditionPointer.asFunction();
print(intptrAddition(10, 27));
}