c++ - 错误C2664 'BOOL CryptBinaryToStringW(const BYTE *,DWORD,DWORD,LPWSTR,DWORD *)' : cannot convert argument 4 from 'std::unique_ptr' to 'LPWSTR'

标签 c++ c++11 compiler-errors

编译C++项目时出现以下错误。

Error C2664 'BOOL CryptBinaryToStringW(const BYTE *,DWORD,DWORD,LPWSTR,DWORD *)': cannot convert argument 4 from 'std::unique_ptr>' to 'LPWSTR'



在下面的代码行中:
CryptBinaryToString(reinterpret_cast<const BYTE*>(strData.c_str()), dwSize,
        dwOptions, pwszBuffer, &dwLength);

而且我也收到以下错误:

Error C2679 binary '=': no operator found which takes a right-hand operand of type 'std::unique_ptr>' (or there is no acceptable conversion)



在下面的行:
sBase64 = pwszBuffer;

下面是完整的代码:
bool EMRReader::EncodeBase64(DWORD dwSize, const std::string& strData, wstring& sBase64)
{
    DWORD dwOptions = CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF;
    DWORD dwLength = 0;

    BOOL bRet = CryptBinaryToString(reinterpret_cast<const BYTE*>(strData.c_str()), dwSize,
        dwOptions, 0, &dwLength);

    if (!bRet)
        return bRet;

    std::unique_ptr<std::wstring> pwszBuffer = std::make_unique<std::wstring>(dwLength + 1);
    if (!pwszBuffer)
        return FALSE;

    SecureZeroMemory(pwszBuffer.get(), (dwLength + 1) * sizeof(wchar_t));
    CryptBinaryToString(reinterpret_cast<const BYTE*>(strData.c_str()), dwSize,
        dwOptions, pwszBuffer, &dwLength);

    sBase64 = pwszBuffer;

    return TRUE;
}

谁能帮我解决这些错误?

最佳答案

您正在将 std::unique_ptr <wstring>对象分配给不允许的wstring类型的变量。如果要将pwszBuffer的值分配给wstring类型的变量,则应获取unique_ptr的值,然后将其分配给该变量。

您可以通过调用std::unique_ptr运算符来获取*的值:
sBase64 = *pwszBuffer;
编辑:如果要将std::unique_ptr传递给函数,则有两种方法:

  • 通过引用传递它:

  • void func(std::unique_ptr<std::wstring>& input_ptr) {
        // Do something...
    }
    

    然后简单地使用它:

    std::unique_ptr<std::wstring> function_input;
    func(function_input);
    

    或2.如果要按值传递它,请移动它:

    void func(std::unique_ptr<std::wstring>& 
    input_ptr) {
        // Do something...
    }
    

    然后用 std::move 传递它:

    std::unique_ptr<std::wstring> function_input;
    func(std::move(function_input));
    

    您应该意识到,在这种情况下,移动function_input后,它不拥有任何内容并持有一个nullptr,而不应将其从func中使用

    related

    关于c++ - 错误C2664 'BOOL CryptBinaryToStringW(const BYTE *,DWORD,DWORD,LPWSTR,DWORD *)' : cannot convert argument 4 from 'std::unique_ptr' to 'LPWSTR' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58032220/

    相关文章:

    c++ - "AnySTLContainer<int>"c++ 的模板

    c++ - 如何在 centos 6 上恢复系统 gcc 编译器

    exception - 捕获 block 避免编译错误?

    cocoa - 构建 32 位 OS X 应用程序时出错?

    TypeScript 错误 "Cannot read property ' 导出“未定义”

    c++ - 使用函数调用初始化枚举值

    c++ - C 预处理器在字符串文字中插入/追加标记

    c++ - 模板外部(与外部模板相比)

    带有运算符的 std::array 的 C++11 类型别名

    c++ - 像 C::C(const C&&) 这样的构造函数我们怎么调用它?除了禁止从 const 移动外,还有其他用途吗?