The Connected Storage API uses Windows::Storage::Streams::Buffer instances to pass data to and from an application. Because WinRT types cannot expose raw pointers, access to the data of a Buffer instance occurs through DataReader and DataWriter classes. However, Buffer also implements the COM interface IBufferByteAccess, which makes it possible to obtain a pointer directly to the buffer data.
IUnknown* unknown = reinterpret_cast<IUnknown*>(buffer);
Microsoft::WRL::ComPtr<IBufferByteAccess> bufferByteAccess;
HRESULT hr = unknown->QueryInterface(_uuidof(IBufferByteAccess), &bufferByteAccess);
if (FAILED(hr))
return nullptr;
byte* bytes = nullptr;
bufferByteAccess->Buffer(&bytes);
For example, the following code sample shows how to create a buffer that holds the current system time. Since buffers have a separate capacity and length value it is necessary to explicitly set both the capacity and length. By default, the length is 0.
inline byte* GetBufferData(Windows::Storage::Streams::IBuffer^ buffer)
{
using namespace Windows::Storage::Streams;
IUnknown* unknown = reinterpret_cast<IUnknown*>(buffer);
Microsoft::WRL::ComPtr<IBufferByteAccess> bufferByteAccess;
HRESULT hr = unknown->QueryInterface(_uuidof(IBufferByteAccess), &bufferByteAccess);
if (FAILED(hr))
return nullptr;
byte* bytes = nullptr;
bufferByteAccess->Buffer(&bytes);
return bytes;
}
IBuffer^ WrapRawBuffer( void* ptr, size_t size )
{
using namespace Windows::Storage::Streams;
//uint32 size = sizeof(FILETIME);
Buffer^ buffer = ref new Buffer(size);
buffer->Length = size;
memcpy(GetBufferData(buffer),ptr,size);
return buffer;
};