toNativeUtf8WithLength static method
Convert Dart string to native UTF-8 with byte length
Returns a record with the pointer and the UTF-8 byte length. Use this when you need to pass the length to C functions.
Example:
final (ptr, len) = StringUtils.toNativeUtf8WithLength("Hello世界", manager);
// ptr points to UTF-8 bytes, len = 11 (not 7!)
Implementation
static (Pointer<Char>, int) toNativeUtf8WithLength(String str, MemoryManager manager) {
final nativeStr = str.toNativeUtf8();
final byteLength = nativeStr.length; // This gives the UTF-8 byte count
manager._allocatedPointers.add(nativeStr);
return (nativeStr.cast<Char>(), byteLength);
}