Skip to content

ObjC: Should generate a custom method to allow efficient exchange of data with NSData. #283

Closed
@brianquinlan

Description

@brianquinlan

Conceptually something like this:

class NSData  extends NSObject {
  factory Data.fromUint8List(Uint8List l) {
    final f = pffi.calloc<ffi.Uint8>(l.length);
    try {
      f.asTypedList(l.length).setAll(0, l);

      return NSData.dataWithBytes_length_(_lib, f.cast(), l.length);
    } finally {
      pffi.calloc.free(f);
    }
  }

  Uint8List get uInt8List {
    final rawBytes = bytes;
    if (rawBytes.address == 0) {
      return Uint8List(0);
    } else {
      // This is unsafe! It is only a view into the underlying NSData!
      return rawBytes.cast<ffi.Uint8>().asTypedList(length);
    }
  }
}

I think that the memory unsafety can be fixed with some effort:

class _NSDataUint8List implements Uint8List, Finalizable {
...
}

  Uint8List get uInt8List {
    final rawBytes = bytes;
    if (rawBytes.address == 0) {
      return Uint8List(0);
    } else {
      retain(); // Keep a reference alive so long as the data is being accessed.
      final uintList = _NSDataUint8List(rawBytes.cast<ffi.Uint8>().asTypedList(length));
      finalizer.attach(uintList, ....) // calls release on this NSData instance.
      return uintList;
    }
  }
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Status

    Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions