Files
sdk/samples/ffi/sample_ffi_functions_callbacks_closures.dart
Daco Harkes 0768228750 [ffi] Format samples and benchmarks with Dart 3.8
Change-Id: I4f8e695ac648becc0de3466b6ba2058cbae7c408
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/422103
Commit-Queue: Bob Nystrom <rnystrom@google.com>
Reviewed-by: Bob Nystrom <rnystrom@google.com>
Auto-Submit: Daco Harkes <dacoharkes@google.com>
Commit-Queue: Daco Harkes <dacoharkes@google.com>
2025-04-11 07:53:45 -07:00

73 lines
2.0 KiB
Dart

// Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:ffi';
import 'package:expect/expect.dart';
import 'dylib_utils.dart';
void main() {
print('start main');
doDynamicLinking();
int counter = 0;
void closure() {
counter++;
}
// C holds on to this closure through a `Dart_PersistentHandle`.
registerClosureCallback(closure);
// Some time later this closure can be invoked.
invokeClosureCallback();
Expect.equals(1, counter);
// When C is done it needs to stop holding on to the closure such that the
// Dart GC can collect the closure.
releaseClosureCallback();
print('end main');
}
final testLibrary = dlopenPlatformSpecific("ffi_test_functions");
final registerClosureCallback = testLibrary
.lookupFunction<Void Function(Handle), void Function(Object)>(
"RegisterClosureCallback",
);
final invokeClosureCallback = testLibrary
.lookupFunction<Void Function(), void Function()>("InvokeClosureCallback");
final releaseClosureCallback = testLibrary
.lookupFunction<Void Function(), void Function()>("ReleaseClosureCallback");
void doClosureCallback(Object callback) {
final callback_as_function = callback as void Function();
callback_as_function();
}
final closureCallbackPointer = Pointer.fromFunction<Void Function(Handle)>(
doClosureCallback,
);
void doDynamicLinking() {
Expect.isTrue(NativeApi.majorVersion == 2);
Expect.isTrue(NativeApi.minorVersion >= 2);
final initializeApi = testLibrary
.lookupFunction<
IntPtr Function(Pointer<Void>),
int Function(Pointer<Void>)
>("InitDartApiDL");
Expect.isTrue(initializeApi(NativeApi.initializeApiDLData) == 0);
final registerClosureCallback = testLibrary
.lookupFunction<Void Function(Pointer), void Function(Pointer)>(
"RegisterClosureCallbackFP",
);
registerClosureCallback(closureCallbackPointer);
}