Skip to content

Instantly share code, notes, and snippets.

@kennykerr
Last active January 17, 2022 15:13
Show Gist options
  • Save kennykerr/39752b796e774957f4d55d1b4edd79cc to your computer and use it in GitHub Desktop.
Save kennykerr/39752b796e774957f4d55d1b4edd79cc to your computer and use it in GitHub Desktop.
How to implement a custom Windows::Storage buffer with C++/WinRT
struct __declspec(uuid("905a0fef-bc53-11df-8c49-001e4fc686da")) IBufferByteAccess : ::IUnknown
{
virtual HRESULT __stdcall Buffer(uint8_t** value) = 0;
};
struct CustomBuffer : implements<CustomBuffer, IBuffer, IBufferByteAccess>
{
std::vector<uint8_t> m_buffer;
uint32_t m_length{};
CustomBuffer(uint32_t size) :
m_buffer(size)
{
}
uint32_t Capacity() const
{
return m_buffer.size();
}
uint32_t Length() const
{
return m_length;
}
void Length(uint32_t value)
{
if (value > m_buffer.size())
{
throw hresult_invalid_argument();
}
m_length = value;
}
HRESULT __stdcall Buffer(uint8_t** value) final
{
*value = m_buffer.data();
return S_OK;
}
};
IAsyncAction SampleUsage()
{
FileOpenPicker picker;
picker.FileTypeFilter().Append(L".txt");
picker.SuggestedStartLocation(PickerLocationId::PicturesLibrary);
StorageFile file = co_await picker.PickSingleFileAsync();
if (file == nullptr)
{
co_return;
}
IRandomAccessStream stream = co_await file.OpenAsync(FileAccessMode::Read);
IBuffer buffer = make<CustomBuffer>(100);
co_await stream.ReadAsync(buffer, buffer.Capacity(), InputStreamOptions::None);
com_ptr<IBufferByteAccess> byte_access = buffer.as<IBufferByteAccess>();
uint8_t* bytes{};
byte_access->Buffer(&bytes);
WINRT_TRACE("%.*s", buffer.Length(), bytes);
}
@alexmercerind
Copy link

Hello,
I seem to get C++ nonvirtual function cannot be declared with 'final' modifier at following line:

HRESULT __stdcall Buffer(uint8_t** value) final

Removing the final removes the error, but I don't know if that's fine to do.
I have not much experience in C++/WinRT in general, your advice would be great.

Thanks.

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