Skip to content

Instantly share code, notes, and snippets.

@rileymjohnson
Last active August 30, 2023 12:22
Show Gist options
  • Save rileymjohnson/d3e559d6be154db9ceb8549a78584b56 to your computer and use it in GitHub Desktop.
Save rileymjohnson/d3e559d6be154db9ceb8549a78584b56 to your computer and use it in GitHub Desktop.
Load a WinRT component from a DLL without registration
#include <winrt/base.h>
#include <type_traits>
#include <hstring.h>
template <typename T>
winrt::impl::com_ref<T> load_winrt_component_from_dll(const winrt::hstring& dll_file)
{
WINRT_ASSERT(std::is_base_of_v<winrt::Windows::Foundation::IUnknown, T>, "T must inherit from Windows::Foundation::IUnknown");
INT32(__stdcall * get_activation_factory)(void*, void**) { nullptr };
winrt::impl::load_runtime_function(dll_file.c_str(), "DllGetActivationFactory", get_activation_factory, nullptr);
winrt::check_pointer(get_activation_factory);
const winrt::hstring name(winrt::name_of<T>());
winrt::com_ptr<winrt::impl::abi_t<winrt::Windows::Foundation::IActivationFactory> > factory{ nullptr };
INT32 result = (*get_activation_factory)(static_cast<HSTRING>(winrt::get_abi(name)), factory.put_void());
winrt::check_bool(result == 0);
winrt::com_ptr<winrt::impl::unknown_abi> base_instance{ nullptr };
result = factory->ActivateInstance(base_instance.put_void());
winrt::check_bool(result == 0);
winrt::detach_abi(factory);
return { base_instance.as<T>() };
}
// Example usage:
int main() {
const winrt::hstring dll_file = L"C:/Users/riley/source/repos/mycomponent/x64/Debug/mycomponent/mycomponent.dll";
const auto component = load_winrt_component_from_dll<winrt::mycomponent::Class>(dll_file);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment