toBstr method

BSTR toBstr()

Converts this Dart string to a COM BSTR.

A BSTR is allocated using SysAllocStringLen and initialized with the UTF-16 contents of this string.

The returned BSTR owns the underlying BSTR and must be released using SysFreeString, unless its lifetime is bound to an Arena.

Example:

final bstr = 'Hello'.toBstr();
// Use the BSTR with COM APIs.
SysFreeString(bstr); // Remember to free when done.

Implementation

BSTR toBstr() {
  final length = codeUnits.length;
  final bstr = SysAllocStringLen(null, length);
  if (bstr.isNull) throw StateError('Failed to allocate memory for BSTR.');
  bstr.cast<WCHAR>().asTypedList(length).setAll(0, codeUnits);
  return .new(bstr);
}