繁体   English   中英

将字符串传递给接受char指针的函数

[英]Passing string to function which accepts pointer to char

我使用C语言的OpenSSL库已经很长时间了,但是现在我需要迁移到C ++。 OpenSSL的文档像这样描述MD5功能。

unsigned char *MD5(const unsigned char *d, unsigned long n,
              unsigned char *md);

我想将string类型的变量传递给该函数,但它仅接受char * 是否可以在C ++中直接将string传递给char *类型的参数? (我不想对string类型的变量使用额外的操作)

您可以使用std::string运动的c_str成员函数。

std::string data;
// load data somehow
unsigned char md[16] = { };
unsigned char *ret = MD5(reinterpret_cast<const unsigned char*>(data.c_str()),
                         data.size(),
                         md);

如果要消除丑陋的强制转换运算符,请定义一个字符串类,该字符串类包含unsigned char而不是char并使用它。

typedef std::basic_string<unsigned char> ustring;
ustring data;
unsigned char *ret = MD5(data.c_str(), data.size(), md);

请注意,这可能会在以后使您头痛。 MD5将无符号的char指针作为参数。 这是一个线索,它实际上不是字符串,而是指向字节的指针。

在您的程序中,如果您开始将字节向量存储在std :: string中,则最终将使用包含零的字节向量来初始化字符串,这可能会导致难以检测到该行的错误。

将所有字节向量存储在std::vector<unsigned char> (或std::vector<uint8_t>安全,因为这会强制安全初始化。

std::vector<unsigned char> plaintext;
// initialise plaintext here
std::vector<unsigned char> my_hash(16);
MD5(plaintext.data(), plaintext.size(), &my_hash[0]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM