-
Notifications
You must be signed in to change notification settings - Fork 52
/
mylib.dart
48 lines (37 loc) · 1.41 KB
/
mylib.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import 'dart:ffi';
import 'dart:io';
import 'package:ffi/ffi.dart';
import './bindings.dart';
const DYNAMIC_LIBRARY_FILE_NAME_ANDROID = "libexample.so";
const DYNAMIC_LIBRARY_FILE_NAME_MACOS = "libexample.dylib";
/// Wraps the native functions and converts specific data types in order to
/// handle C strings.
class Greeter {
static final GreeterBindings _bindings =
GreeterBindings(Greeter._loadLibrary());
static DynamicLibrary _loadLibrary() {
return Platform.isAndroid
? DynamicLibrary.open(DYNAMIC_LIBRARY_FILE_NAME_ANDROID)
: Platform.isMacOS
? DynamicLibrary.open(DYNAMIC_LIBRARY_FILE_NAME_MACOS)
: DynamicLibrary.process();
}
/// Computes a greeting for the given name using the native function
static String greet(String name) {
final ptrName = name.toNativeUtf8().cast<Int8>();
// Native call
final ptrResult = _bindings.rust_greeting(ptrName);
// Cast the result pointer to a Dart string
final result = ptrResult.cast<Utf8>().toDartString();
// Clone the given result, so that the original string can be freed
final resultCopy = "" + result;
// Free the native value
Greeter._free(result);
return resultCopy;
}
/// Releases the memory allocated to handle the given (result) value
static void _free(String value) {
final ptr = value.toNativeUtf8().cast<Int8>();
return _bindings.rust_cstr_free(ptr);
}
}