ActivateClass function winrt

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

Activates the specified Windows Runtime class in the className.

This returns the WinRT IInspectable interface, which is a subclass of IUnknown.

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> ActivateClass(String className,
    {Allocator allocator = calloc}) {
  // Create a HSTRING representing the object
  final hClassName = convertToHString(className);
  final inspectablePtr = allocator<COMObject>();

  try {
    final hr = RoActivateInstance(hClassName, inspectablePtr.cast());
    if (FAILED(hr)) throw WindowsException(hr);
    // Return a pointer to the relevant class
    return inspectablePtr;
  } on WindowsException catch (e) {
    // If RoActivateInstance 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 = RoActivateInstance(hClassName, inspectablePtr.cast());
      if (FAILED(hr)) throw WindowsException(hr);
      // Return a pointer to the relevant class
      return inspectablePtr;
    }
    rethrow;
  } finally {
    WindowsDeleteString(hClassName);
  }
}