将"unsigned char*"转换为"char*"(和字符串)

cal*_*eve 1 c++ visual-studio-2015

我正在与libsodium库一起开展宠物项目,发现将unsigned char*转换为char*比我想象的要简单.此外,我首先感到困惑,因为测试是在Release模式下传递的,稍后我才发现它们没有在调试模式下传递.所以我想出了以下内容:

std::string string_from_uchar(const unsigned char * c, unsigned long long lc)
    {
        unsigned char * cc = new unsigned char[lc+1] ;
        std::strncpy((char *) cc, (char *) c, lc);
        cc[lc] = 0;
        char* cr = reinterpret_cast<char *> (cc);
        std::string ret(cr);
        delete[](cr);
        return ret;
    }
Run Code Online (Sandbox Code Playgroud)

虽然它现在通过了测试,但如果有人能够检查它是否是正确的方法(例如,它是否适用于gcc或clang等其他环境,我感激不尽).

Lig*_*ica 5

你大量过度思考这个问题.

副本是冗余的,因为额外的动态分配和添加空终止符(因为std::string有一个构造函数只接受这种场合的长度参数).

各种各样的char可以别名,所以简单:

std::string string_from_uchar(const unsigned char * c, unsigned long long lc)
{
    return std::string((const char*)c, lc);
}
Run Code Online (Sandbox Code Playgroud)

实际上,如果你使用带范围的构造函数,你甚至不需要强制转换:

std::string string_from_uchar(const unsigned char * c, unsigned long long lc)
{
    return std::string(c, c + lc);
}
Run Code Online (Sandbox Code Playgroud)

它甚至几乎不保证自己的功能.

  • 谢谢你的例子!你刚忘了`c +`;-).这里:http://coliru.stacked-crooked.com/a/14f4c576def38129 (3认同)