CreateActivationFactory function winrt

Pointer<COMObject> CreateActivationFactory(
  1. String className,
  2. String iid, {
  3. Allocator allocator = calloc,
})

Creates the activation factory for the specified runtime class using the className and iid.

final object = CreateActivationFactory(
    'Windows.Globalization.PhoneNumberFormatting.PhoneNumberFormatter',
    IID_IPhoneNumberFormatterStatics);
final phoneNumberFormatter = IPhoneNumberFormatterStatics(object);

It is the caller's responsibility to deallocate the returned pointer when they are finished with it. A FFI Arena may be passed as a custom allocator for ease of memory management.

Implementation

Pointer<COMObject> CreateActivationFactory(String className, String iid,
    {Allocator allocator = calloc}) {
  // Create a HSTRING representing the object
  final hClassName = convertToHString(className);
  final pIID = GUIDFromString(iid);
  final activationFactoryPtr = allocator<COMObject>();

  try {
    final hr =
        RoGetActivationFactory(hClassName, pIID, activationFactoryPtr.cast());
    if (FAILED(hr)) throw WindowsException(hr);
    // Return a pointer to the relevant class
    return activationFactoryPtr;
  } on WindowsException catch (e) {
    // If RoGetActivationFactory fails because combase hasn't been loaded yet
    // then load combase so that it "just works" for apartment-agnostic code.
    if (e.hr == CO_E_NOTINITIALIZED) {
      _initializeMTA();
      final hr =
          RoGetActivationFactory(hClassName, pIID, activationFactoryPtr.cast());
      if (FAILED(hr)) throw WindowsException(hr);
      // Return a pointer to the relevant class
      return activationFactoryPtr;
    }
    rethrow;
  } finally {
    free(pIID);
    WindowsDeleteString(hClassName);
  }
}