我有一个dart:ffi
Struct,包含一个指向Char和int的指针len
class UnnamedStruct1 extends ffi.Struct {
external ffi.Pointer<ffi.Char> ptr;
@ffi.Int()
external int len;
}
应该表示String
(稍后解析为Uri)如何将其转换为字符串
您可以创建一个函数将UnnamedStruct1实例转换为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);
}
应该可以了
@mozzarella在这里建议的方法fromUtf8
已被弃用
和cast()
目标错误的类型(应该是Utf8,而不是Uint8)
但总体上(希望)指出我在正确的方向,谢谢!
.cast<Utf8>()
有可能会爆炸
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);