如何在C ++中的WinRT IBuffer中包装char *缓冲区 [英] How to wrap a char* buffer in a WinRT IBuffer in C++
问题描述
我想实现一个包装char *缓冲区的C ++ WinRT IBuffer,因此我可以将其与接受IBuffer ^参数的WinRT WriteAsync / ReadAsync操作一起使用。
I want to implement a C++ WinRT IBuffer that wraps a char* buffer, so i can use it with WinRT WriteAsync/ReadAsync operations that accept an IBuffer^ parameter.
编辑1(澄清)
我要避免数据复制。
推荐答案
大部分复制自 http://jeremiahmorrill.wordpress.com/2012 / 05/11 / http-winrt-client-for-c / ,但是可以直接包装我自己的字节[]:
Mostly copied from http://jeremiahmorrill.wordpress.com/2012/05/11/http-winrt-client-for-c/ but adapted to directly wrap my own byte[]:
NativeBuffer.h:
NativeBuffer.h:
#pragma once
#include <wrl.h>
#include <wrl/implements.h>
#include <windows.storage.streams.h>
#include <robuffer.h>
#include <vector>
// todo: namespace
class NativeBuffer :
public Microsoft::WRL::RuntimeClass<Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::RuntimeClassType::WinRtClassicComMix>,
ABI::Windows::Storage::Streams::IBuffer,
Windows::Storage::Streams::IBufferByteAccess>
{
public:
virtual ~NativeBuffer()
{
}
STDMETHODIMP RuntimeClassInitialize(byte *buffer, UINT totalSize)
{
m_length = totalSize;
m_buffer = buffer;
return S_OK;
}
STDMETHODIMP Buffer(byte **value)
{
*value = m_buffer;
return S_OK;
}
STDMETHODIMP get_Capacity(UINT32 *value)
{
*value = m_length;
return S_OK;
}
STDMETHODIMP get_Length(UINT32 *value)
{
*value = m_length;
return S_OK;
}
STDMETHODIMP put_Length(UINT32 value)
{
m_length = value;
return S_OK;
}
private:
UINT32 m_length;
byte *m_buffer;
};
要创建IBuffer:
To create the IBuffer:
Streams::IBuffer ^CreateNativeBuffer(LPVOID lpBuffer, DWORD nNumberOfBytes)
{
Microsoft::WRL::ComPtr<NativeBuffer> nativeBuffer;
Microsoft::WRL::Details::MakeAndInitialize<NativeBuffer>(&nativeBuffer, (byte *)lpBuffer, nNumberOfBytes);
auto iinspectable = (IInspectable *)reinterpret_cast<IInspectable *>(nativeBuffer.Get());
Streams::IBuffer ^buffer = reinterpret_cast<Streams::IBuffer ^>(iinspectable);
return buffer;
}
调用读取数据(lpBuffer为字节[]):
And the call to read data (lpBuffer is the byte[]):
Streams::IBuffer ^buffer = CreateNativeBuffer(lpBuffer, nNumberOfbytes);
create_task(randomAccessStream->ReadAsync(buffer, (unsigned int)nNumberOfBytesToRead, Streams::InputStreamOptions::None)).wait();
我不确定ComPtr是否需要清理,因此欢迎提供有关内存管理的任何建议。
I am not so sure if the ComPtr needs some cleanup, so any suggestions regarding memory management are welcome.
这篇关于如何在C ++中的WinRT IBuffer中包装char *缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!