0

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

Francesco Iapicca
  • 2,618
  • 5
  • 40
  • 85

2 Answers2

1

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

mozzarella
  • 43
  • 8
0

the method fromUtf8 suggested here by @mozzarella is deprecated
and the cast() target the wrong Type (should be Utf8, not Uint8)
but overall (hopefully) pointed me in the right direction, thanks!

I'll wait before accepting anything as there is a chance that
.cast<Utf8>() will blow up

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

  @ffi.Int()
  external int len;
}


final UnnamedStruct1 struct = //...
final string = struct.ptr
        .cast<Utf8>()
        .toDartString(length: struct.ref.uri.len);

Francesco Iapicca
  • 2,618
  • 5
  • 40
  • 85