setString method

int setString(
  1. String string
)

Writes the given Dart string into this buffer as UTF-16 code units.

The caller must ensure that the underlying allocation is large enough to hold (string.length + 1) UTF-16 code units, including the terminating NUL.

Writing beyond the allocated memory results in undefined behavior.

Returns the total number of bytes written, including the NUL terminator.

Example:

final buffer = wsalloc(20);
final bytesWritten = buffer.setString("Hello");
print(bytesWritten); // Outputs: 12 (5 UTF-16 code units + 2 NUL)
free(buffer);

Implementation

int setString(String string) {
  final units = string.codeUnits;
  final len = units.length;

  final pwstr = cast<WCHAR>().asTypedList(len + 1)..setAll(0, units);
  pwstr[len] = 0;

  return (len + 1) * sizeOf<WCHAR>();
}