toCString function

Pointer<Utf8> toCString(
  1. String s
)

toNativeUtf8 with the two checks a C string needs and a Dart String does not enforce, applied to every string parameter that crosses the ABI (model ids, api keys, base URLs, dir paths, base64 payloads, media types, JSON text):

  • Interior NUL. toNativeUtf8 writes it verbatim, and the C side's CStr::from_ptr stops there — the argument is silently truncated at the NUL rather than rejected.
  • Unpaired surrogate. toNativeUtf8 substitutes U+FFFD (documented in package:ffi's StringUtf8Pointer.toNativeUtf8), so the argument is silently corrupted rather than rejected.

Both are catchable FormatExceptions here instead of silence there.

Implementation

Pointer<Utf8> toCString(String s) {
  final nul = s.codeUnits.indexOf(0);
  if (nul >= 0) {
    throw FormatException(
        'argument contains a NUL at index $nul; a C string ends there', s, nul);
  }
  _checkSurrogates(s, 'argument');
  return s.toNativeUtf8();
}