CreateObject function winrt

Pointer<COMObject> CreateObject(
  1. String className,
  2. String iid
)

Creates a WinRT object.

final object = CreateObject('Windows.Globalization.Calendar', IID_ICalendar);
final calendar = ICalendar.fromRawPointer(object);

Implementation

Pointer<COMObject> CreateObject(String className, String iid) {
  final hstrClass = calloc<HSTRING>();
  final lpClassName = className.toNativeUtf16();
  final inspectablePtr = calloc<COMObject>();
  final riid = calloc<GUID>();
  final classPtr = calloc<Pointer>();
  final iidPtr = iid.toNativeUtf16();
  final classNamePtr = className.toNativeUtf16();

  try {
    // Create a HSTRING representing the object
    var hr = WindowsCreateString(classNamePtr, className.length, hstrClass);
    if (FAILED(hr)) {
      throw WindowsException(hr);
    }
    // Activates the specified Windows Runtime class. This returns the WinRT
    // IInspectable interface, which is a subclass of IUnknown.
    hr = RoActivateInstance(hstrClass.value, inspectablePtr.cast());
    if (FAILED(hr)) {
      throw WindowsException(hr);
    }

    // Create an IID for the interface required
    hr = IIDFromString(iidPtr, riid);
    if (FAILED(hr)) {
      throw WindowsException(hr);
    }

    // Now use IInspectable to navigate to the relevant interface
    final inspectable = IInspectable(inspectablePtr);
    hr = inspectable.queryInterface(riid, classPtr);
    if (FAILED(hr)) {
      throw WindowsException(hr);
    }

    // Return a pointer to the relevant class
    return classPtr.cast();
  } finally {
    free(classNamePtr);
    free(iidPtr);
    free(riid);
    free(inspectablePtr);
    free(lpClassName);
    free(hstrClass);
  }
}