Skip to content

Commit c0a6336

Browse files
committed
Finalizers for native lightweight objects
1 parent caec35f commit c0a6336

File tree

3 files changed

+23
-2
lines changed

3 files changed

+23
-2
lines changed

lib/backend/fs.dart

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -241,7 +241,13 @@ class TransferFileOperation extends BaseFileSystemOperation<bool> {
241241
}
242242
}
243243

244-
extension type File._(Pointer<GFile> _handle) implements Object {
244+
final NativeFinalizer _finalizer = NativeFinalizer(Native.addressOf(obj_unref));
245+
246+
class File implements Finalizable {
247+
File._(this._handle) {
248+
_finalizer.attach(this, _handle.cast());
249+
}
250+
245251
static File fromRawPath(Pointer<Char> path) {
246252
final res = file_new(path);
247253

@@ -257,6 +263,8 @@ extension type File._(Pointer<GFile> _handle) implements Object {
257263
});
258264
}
259265

266+
final Pointer<GFile> _handle;
267+
260268
String get path => file_path(_handle).cast<Utf8>().toDartString();
261269
File? get parent {
262270
final parent = file_parent(_handle);
@@ -359,7 +367,12 @@ extension type File._(Pointer<GFile> _handle) implements Object {
359367
}
360368
}
361369

362-
extension type FileInfo._(Pointer<GFileInfo> _handle) {
370+
class FileInfo implements Finalizable {
371+
FileInfo._(this._handle) {
372+
_finalizer.attach(this, _handle.cast());
373+
}
374+
375+
final Pointer<GFileInfo> _handle;
363376
String? getName() {
364377
final name = fileinfo_get_name(_handle);
365378
if (name == nullptr) return null;

lib/backend/fs_native.dart

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,9 @@ final class GList extends Struct {
3333
external final Pointer<GList> previous;
3434
}
3535

36+
@Native<Void Function(Pointer<Void>)>()
37+
external void obj_unref(Pointer<Void> obj);
38+
3639
@Native<Pointer<GCancellable> Function()>()
3740
external Pointer<GCancellable> cancellable_new();
3841

src/src/lib.zig

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -482,3 +482,8 @@ pub export fn error_domain_name(err: *c.GError) [*c]const u8 {
482482
pub export fn list_destroy(list: [*c]c.GList) void {
483483
c.g_list_free(list);
484484
}
485+
486+
// -------- MEMORY -------- //
487+
pub export fn obj_unref(obj: ?*anyopaque) void {
488+
c.g_object_unref(obj);
489+
}

0 commit comments

Comments
 (0)