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

Passing string to function which accepts pointer to char

本文关键字:字符 指针 函数 字符串      更新时间:2023-10-16

我已经在 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 s 而不是 char s 的字符串类并使用它。

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

只是一个小笔记,这可能会让你以后省去头痛。MD5 将无符号字符指针作为参数。这是一个线索,它实际上不是一个字符串,而是一个指向字节的指针。

在你的程序中,如果你开始在 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]);