Skip to content

Instantly share code, notes, and snippets.

@kennykerr
Last active September 13, 2022 04:54
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kennykerr/f1d941c2d26227abbf762481bcbd84d3 to your computer and use it in GitHub Desktop.
Save kennykerr/f1d941c2d26227abbf762481bcbd84d3 to your computer and use it in GitHub Desktop.
How to use IMemoryBufferByteAccess with C++/WinRT
#include "winrt/Windows.Foundation.h"
struct __declspec(uuid("5b0d3235-4dba-4d44-865e-8f1d0e4fd04d")) __declspec(novtable) IMemoryBufferByteAccess : ::IUnknown
{
virtual HRESULT __stdcall GetBuffer(uint8_t** value, uint32_t* capacity) = 0;
};
using namespace winrt;
using namespace Windows::Foundation;
int main()
{
init_apartment();
MemoryBuffer buffer(10);
IMemoryBufferReference ref = buffer.CreateReference();
WINRT_ASSERT(ref.Capacity() == 10);
{
auto interop = ref.as<IMemoryBufferByteAccess>();
uint8_t* value{};
uint32_t value_size{};
check_hresult(interop->GetBuffer(&value, &value_size));
WINRT_ASSERT(value_size == 10);
sprintf_s(reinterpret_cast<char*>(value), value_size, "C++/WinRT");
}
{
auto interop = ref.as<IMemoryBufferByteAccess>();
uint8_t* value{};
uint32_t value_size{};
check_hresult(interop->GetBuffer(&value, &value_size));
WINRT_ASSERT(value_size == 10);
printf("%s\n", reinterpret_cast<char*>(value));
}
}
@Youw
Copy link

Youw commented May 1, 2020

Don't forget to include #include <wrl/client.h> to have ::IUnknown and HRESULT

@dwcullop
Copy link

Exactly what I was looking for! Thank you!

@kennykerr
Copy link
Author

@Youw unknwn.h will suffice.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment