简体   繁体   English

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

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

I've been working with OpenSSL library in C for a long time, but now I need to migrate to C++. 我使用C语言的OpenSSL库已经很长时间了,但是现在我需要迁移到C ++。 OpenSSL's docs describe MD5 function like this. OpenSSL的文档像这样描述MD5功能。

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

I want to pass variable of type string to that function, but it accepts only char * . 我想将string类型的变量传递给该函数,但它仅接受char * Is it possible to pass string to parameter of type char * directly in C++? 是否可以在C ++中直接将string传递给char *类型的参数? (I don't want to use extra manipulation with variable of type string ) (我不想对string类型的变量使用额外的操作)

You could use the c_str member function that std::string sports. 您可以使用std::string运动的c_str成员函数。 Example

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);

If you want to do away with the ugly cast operator, define a string class that holds unsigned char s instead of char s and use that. 如果要消除丑陋的强制转换运算符,请定义一个字符串类,该字符串类包含unsigned char而不是char并使用它。

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

just a little note, which may save you a headache later on. 请注意,这可能会在以后使您头痛。 MD5 takes an unsigned char pointer as a parameter. MD5将无符号的char指针作为参数。 This is a clue that it's actually not a string, but a pointer to bytes. 这是一个线索,它实际上不是字符串,而是指向字节的指针。

In your program if you start storing byte vectors in a std::string, you're eventually going to initialise a string with a byte vector containing a zero, which opens the possibility of a bug that's difficult to detect down the line. 在您的程序中,如果您开始将字节向量存储在std :: string中,则最终将使用包含零的字节向量来初始化字符串,这可能会导致难以检测到该行的错误。

It is safer to store all your byte vectors in a std::vector<unsigned char> (or std::vector<uint8_t> because this forces safe initialisation. 将所有字节向量存储在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