fromNativeUtf8WithLength static method

String fromNativeUtf8WithLength(
  1. Pointer<Char> pointer,
  2. int length
)

Convert native UTF-8 string with known length to Dart string safely.

Use this method when you have the exact byte length of the string, such as when reading from Oracle's dpiBytes structure which provides both a pointer and length.

Why This Method Exists

Oracle's ODPI-C library returns strings with explicit lengths rather than null-terminated strings. Using fromNativeUtf8 (which expects null-termination) can cause incorrect string parsing or memory access issues.

Parameters

  • pointer: Pointer to the UTF-8 encoded bytes
  • length: The exact byte length of the string (from dpiBytes.length)

Example

// Reading from Oracle result set
final bytes = data.value.asBytes;
final str = StringUtils.fromNativeUtf8WithLength(
  bytes.ptr.cast<Char>(),
  bytes.length,
);

Fallback Behavior

If the standard UTF-8 decoding fails, this method attempts a byte-by-byte decode with allowMalformed: true to handle potentially invalid sequences.

Implementation

static String fromNativeUtf8WithLength(Pointer<Char> pointer, int length) {
  if (pointer == nullptr || length <= 0) {
    return '';
  }
  try {
    return pointer.cast<Utf8>().toDartString(length: length);
  } catch (e) {
    // Fallback: try to read as raw bytes and decode
    try {
      final bytes = <int>[];
      for (var i = 0; i < length; i++) {
        bytes.add(pointer[i]);
      }
      return utf8.decode(bytes, allowMalformed: true);
    } catch (_) {
      throw OracleMemoryException('Failed to convert native string with length $length: $e');
    }
  }
}