我想实现一个包装char *缓冲区的C++ WinRT IBuffer,因此我可以将其与接受IBuffer ^参数的WinRT WriteAsync/ReadAsync操作一起使用。

编辑1(澄清)

我想避免数据复制。

最佳答案

通常是从http://jeremiahmorrill.wordpress.com/2012/05/11/http-winrt-client-for-c/复制而来的,可以直接包装我自己的byte []:

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,请执行以下操作:
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是byte []):
Streams::IBuffer ^buffer = CreateNativeBuffer(lpBuffer, nNumberOfbytes);
create_task(randomAccessStream->ReadAsync(buffer, (unsigned int)nNumberOfBytesToRead, Streams::InputStreamOptions::None)).wait();

我不确定ComPtr是否需要清理,因此欢迎提供有关内存管理的任何建议。

关于c++ - 如何在C++中的WinRT IBuffer中包装char *缓冲区,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10520335/

10-12 20:33