An efficient way to convert ByteData in Dart to unsigned char* in C++?

1,071

This is always going to involve a copy, so is there something more efficient than your for loop? Maybe.

After allocating your Uint8Pointer use asTypedList to convert it to a Uint8List. Now you have access to its copy primitive like setAll and setRange to copy from the source to the destination.

What's the original source of the ByteData? If you knew the size in advance, could you allocate the Uint8Pointer first, convert to typed data and then read directly into that?

Share:
1,071
LvSheng
Author by

LvSheng

Updated on December 16, 2022

Comments

  • LvSheng
    LvSheng over 1 year

    I'm doing it in this way:

    Pointer<Uint8> _byteDataToPointer(ByteData byteData) {
      final uint8List = byteData.buffer.asUint8List();
      final length = uint8List.lengthInBytes;
      final result = allocate<Uint8>(count: length);
    
      for (var i = 0; i < length; ++i) {
        result[i] = uint8List[i];
      }
    
      return result;
    }
    

    Is there a more efficient way like JNIEnv::GetByteArrayRegion in JNI?

    Thank you very much!

  • LvSheng
    LvSheng over 4 years
    Thank you~! asTypedList is what I need!
  • LvSheng
    LvSheng over 4 years
    and the original source of the ByteData is rootBundle.load, I don't find a way to read directly into my Uint8List