将字符串传递给接受指向字符的指针的函数
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
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]);
相关文章:
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 如何循环访问 cpp 中的函数返回的字符指针数组
- 将(N 个字节)无符号字符指针转换为浮点数和双 C++
- 字符指针的 Qt 数组
- C++将常量字符* 指针数组传递给对象
- 为什么不能将字符指针定义为数组?
- 在函数内初始化无符号字符指针将返回空指针
- 将字符指针存储到容器中
- 为什么 strtok_r() 只接受字符数组而不接受字符指针
- 字符指针数组内存分配
- 字符指针不递增?
- 如何在C++中使用字符指针
- 确保字符指针始终指向相同的字符串文字
- C++中的字符指针
- 使用unique_ptr的常量字符指针
- 字符指针不断意外更改
- 将字符指针中的十六进制转换为十进制
- 如何将字符*(字符指针)转换为 PCSZ?
- 在向量中存储字符指针
- 字符指针具有不同的值