1

作为 WinRT C++cx 组件的一部分,std::string用 a 来回转换非托管字节缓冲区(比如表示为 a )的最有效方法是Windows::Web::Http::HttpBufferContent什么?

这是我最终得到的,但它似乎不是很理想:

std::stringHttpBufferContent

std::string m_body = ...;
auto writer = ref new DataWriter();
writer->WriteBytes(ArrayReference<unsigned char>(reinterpret_cast<unsigned char*>(const_cast<char*>(m_body.data())), m_body.length()));
auto content = ref new HttpBufferContent(writer->DetachBuffer());

HttpBufferContentstd::string

HttpBufferContent^ content = ...
auto operation = content->ReadAsBufferAsync();
auto task = create_task(operation);
if (task.wait() == task_status::completed) {
    auto buffer = task.get();
    size_t length = buffer->Length;
    if (length > 0) {
        unsigned char* storage = static_cast<unsigned char*>(malloc(length));
        DataReader::FromBuffer(buffer)->ReadBytes(ArrayReference<unsigned char>(storage, length));
        auto m_body = std::string(reinterpret_cast<char*>(storage), length);
        free(storage);
    }
} else {
    abort();
}

更新:这是我最终使用的版本(您可以轻松地HttpBufferContent^从 an创建一个Windows::Storage::Streams::IBuffer^):

void IBufferToString(IBuffer^ buffer, std::string& string) {
    Array<unsigned char>^ array = nullptr;
    CryptographicBuffer::CopyToByteArray(buffer, &array);  // TODO: Avoid copy
    string.assign(reinterpret_cast<char*>(array->Data), array->Length);
}

IBuffer^ StringToIBuffer(const std::string& string) {
    auto array = ArrayReference<unsigned char>(reinterpret_cast<unsigned char*>(const_cast<char*>(string.data())), string.length());
    return CryptographicBuffer::CreateFromByteArray(array);
}
4

2 回答 2

0

我认为您在当前的 HttpBufferContent 到 std::string 的方法中至少制作了一份不必要的数据副本,您可以通过直接访问 IBuffer 数据来改进这一点,请参阅此处接受的答案:Get a array of bytes out of Windows ::Storage::Streams::IBuffer

于 2015-12-10T14:53:56.263 回答
0

我认为最好使用智能指针(不需要内存管理):

#include <wrl.h>
#include <robuffer.h>
#include <memory>
using namespace Windows::Storage::Streams;
using namespace Microsoft::WRL;

IBuffer^ buffer;
ComPtr<IBufferByteAccess> byte_access;
reinterpret_cast<IInspectable*>(buffer)->QueryInterface(IID_PPV_ARGS(&byte_access));
std::unique_ptr<byte[]> raw_buffer = std::make_unique<byte[]>(buffer->Length);
byte_access->Buffer(raw_buffer.get());
std::string str(reinterpret_cast<char*>(raw_buffer.get())); // just 1 copy
于 2015-12-15T13:08:31.450 回答