0

我有 IStream,我想在 c++ 中将其转换为 base 64 字符串,以便我可以在 C++/cli 中使用它来将其转换为 .net 流。

类似地,我想知道如何将 base 64 字符串转换回 IStream。

4

1 回答 1

0

我的代码使用 ATL CString ...

template<class T>
HRESULT StreamToBase64(IStream* pStream, T &strOut)
{
    // Clear buffer
    strOut.ReleaseBuffer(0);
    if (!pStream)
        return S_OK;

    // Get size
    STATSTG stat;
    pStream->Stat(&stat, STATFLAG_NONAME);
    unsigned iLen = stat.cbSize.LowPart;

    // Seek to start
    LARGE_INTEGER lPos;
    lPos.QuadPart = 0;
    HRESULT hr = pStream->Seek(lPos, SEEK_SET, nullptr);
    if (FAILED(hr))
        return hr;

    // Reserve the memory
    strOut.GetBuffer(Mfx::BinToBase64GetRequiredLength(iLen));
    strOut.ReleaseBuffer(0);

    // Use one line to decode a time. On line of Base64 code has usually 39 chars. We
    // use a nearly 1kb buffer
    const int iBase64LIneLen = 76/4*3;
    BYTE bLine[(1024/iBase64LIneLen)*iBase64LIneLen];
    ULONG bRead;
    while (SUCCEEDED(hr = pStream->Read(bLine, sizeof(bLine), &bRead)) && bRead!=0)
        strOut += T(Mfx::BinToBase64A(bLine, bRead));

    // And seek back to start
    pStream->Seek(lPos, SEEK_SET, nullptr);
    return SUCCEEDED(hr) ? S_OK : hr;
}

HRESULT StreamToBase64(IStream* pStream, CStringA &strOut)
{
    return StreamToBase64<CStringA>(pStream, strOut);
}

HRESULT StreamToBase64(IStream* pStream, CStringW &strOut)
{
    return StreamToBase64<CStringW>(pStream, strOut);
}
于 2019-11-25T09:56:19.247 回答