Skip to content

Instantly share code, notes, and snippets.

@kennykerr
Last active July 9, 2025 19:13
Show Gist options
  • Save kennykerr/175a8609c1073454372cd82ab1cc2586 to your computer and use it in GitHub Desktop.
Save kennykerr/175a8609c1073454372cd82ab1cc2586 to your computer and use it in GitHub Desktop.
#include <Windows.h>
#include "winrt/Windows.Globalization.h"
template <typename Class, typename Interface = winrt::Windows::Foundation::IActivationFactory>
Interface get_factory_from(winrt::param::hstring const& library_name)
{
winrt::impl::library_handle library(winrt::impl::load_library(static_cast<winrt::hstring const&>(library_name).c_str()));
if (!library)
{
return nullptr;
}
winrt::param::hstring class_name = winrt::name_of<Class>();
auto library_call = reinterpret_cast<int32_t(__stdcall*)(void* classId, void** factory)>(WINRT_IMPL_GetProcAddress(library.get(), "DllGetActivationFactory"));
if (!library_call)
{
return nullptr;
}
winrt::Windows::Foundation::IActivationFactory library_factory;
if (0 != library_call(*(void**)(&class_name), winrt::put_abi(library_factory)))
{
return nullptr;
}
Interface result;
if constexpr (std::is_same_v<Interface, winrt::Windows::Foundation::IActivationFactory>)
{
result = library_factory;
}
else
{
result = library_factory.try_as<Interface>();
}
if (result)
{
library.detach();
}
return result;
}
template <typename Class>
Class activate_from(winrt::param::hstring const& library_name)
{
auto factory = get_factory_from<Class, winrt::Windows::Foundation::IActivationFactory>(library_name);
if (!factory)
{
return nullptr;
}
return factory.ActivateInstance<Class>();
}
int main()
{
CO_MTA_USAGE_COOKIE cookie{};
CoIncrementMTAUsage(&cookie);
using namespace winrt::Windows::Globalization;
auto factory = get_factory_from<Calendar>(L"Windows.Globalization.dll");
if (factory)
{
auto calendar = factory.ActivateInstance<Calendar>();
assert(calendar.Year() == 2025);
}
auto calendar = activate_from<Calendar>(L"Windows.Globalization.dll");
if (calendar)
{
assert(calendar.Year() == 2025);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment