Skip to content

Instantly share code, notes, and snippets.

@kbridge
Created December 3, 2023 18:38
Show Gist options
  • Save kbridge/959b772c36b8d491d0d6fde69710b706 to your computer and use it in GitHub Desktop.
Save kbridge/959b772c36b8d491d0d6fde69710b706 to your computer and use it in GitHub Desktop.
demo: call windows runtime from pure c
// please link with "runtimeobject.lib"
#include <roapi.h>
#include <winstring.h>
#include <windows.foundation.h>
#include <stdio.h>
#include <stdlib.h>
#define WIDEN2(x) L ## x
#define WIDEN(x) WIDEN2(x)
#define __WFILE__ WIDEN(__FILE__)
#define CHECK(hr) \
do \
{ \
if (FAILED(hr)) \
{ \
wprintf_s(L"%s:%d: hr = 0x%08X\n", __WFILE__, __LINE__, hr); \
exit(1); \
} \
} \
while (0)
int wmain()
{
HRESULT hr;
hr = RoInitialize(RO_INIT_MULTITHREADED);
CHECK(hr);
{
// some interfaces do not even have a C definition, e.g. IVector<T>, do they have an ABI?
__x_ABI_CWindows_CFoundation_CIUriRuntimeClass *uri;
{
__x_ABI_CWindows_CFoundation_CIUriRuntimeClassFactory *uriFactory;
{
// not found in any .lib file, have to copy this from the header file
//
// cd "C:\Program Files (x86)\Windows Kits\10\Lib\10.0.22621.0"
// findstr /m /s /c:IUriRuntimeClassFactory *
static const IID iid = { 0x44a9796f, 0x723e, 0x4fdf, {0xa2, 0x18, 0x03, 0x3e, 0x75, 0xb0, 0xc0, 0x84 } };
HSTRING_HEADER runtimeClassStringHeader;
HSTRING runtimeClassString;
hr = WindowsCreateStringReference(
RuntimeClass_Windows_Foundation_Uri,
sizeof RuntimeClass_Windows_Foundation_Uri / sizeof(WCHAR) - 1,
&runtimeClassStringHeader,
&runtimeClassString);
CHECK(hr);
hr = RoGetActivationFactory(
runtimeClassString,
&iid,
&uriFactory);
CHECK(hr);
}
{
static const WCHAR uriData[] = L"https://learn.microsoft.com/en-us/cpp/cppcx/wrl/how-to-activate-and-use-a-windows-runtime-component-using-wrl?view=msvc-170";
HSTRING_HEADER uriStringHeader;
HSTRING uriString;
hr = WindowsCreateStringReference(
uriData,
sizeof uriData / sizeof(WCHAR) - 1,
&uriStringHeader,
&uriString);
CHECK(hr);
hr = uriFactory->lpVtbl->CreateUri(uriFactory, uriString, &uri);
CHECK(hr);
}
uriFactory->lpVtbl->Release(uriFactory);
}
{
HSTRING string;
hr = uri->lpVtbl->get_Domain(uri, &string);
CHECK(hr);
wprintf_s(L"domain is \"%s\"\n", WindowsGetStringRawBuffer(string, 0));
WindowsDeleteString(string);
}
{
HSTRING string;
hr = uri->lpVtbl->get_Path(uri, &string);
CHECK(hr);
wprintf_s(L"path is \"%s\"\n", WindowsGetStringRawBuffer(string, 0));
WindowsDeleteString(string);
}
uri->lpVtbl->Release(uri);
}
RoUninitialize();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment