Skip to content

Instantly share code, notes, and snippets.

@kennykerr
Last active Nov 30, 2020
Embed
What would you like to do?
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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment