Search code examples
cdartdart-ffi

How to convert dart:ffi Char to String


I have a dart:ffi Struct that contains a pointer to a Char and int len

class UnnamedStruct1 extends ffi.Struct {
  external ffi.Pointer<ffi.Char> ptr;

  @ffi.Int()
  external int len;
}

it is supposed to represent a String (later to parse as Uri) how do I convert it to a string


Solution

  • you can create a function to convert the UnnamedStruct1 instance to a Dart String

    String unnamedStruct1ToString(UnnamedStruct1 struct) {
      // Cast the pointer to a Pointer<Uint8>
      ffi.Pointer<ffi.Uint8> uint8Pointer = struct.ptr.cast<ffi.Uint8>();
    
      // Create a Dart String from the Utf8 encoded data
      String result = ffi.Utf8.fromUtf8(uint8Pointer, struct.len);
    
      return result;
    }
    
    
    void main() {
      // Assuming you have an instance of UnnamedStruct1 called myStruct
      UnnamedStruct1 myStruct = // ... initialize your struct here
    
      // Convert the struct to a Dart String
      String myString = unnamedStruct1ToString(myStruct);
    
      // Print the resulting string
      print(myString);
    }
    
    

    This should do it