'How would I pass a string to a function argument defined as const unsigned char*?
I copied Base64 encode/decode functions from Stack Overflow. The decode function works great. My problem is with the encode. I get the following error using Visual Studio 2022:
error C2664: 'std::string Base64_encode(const unsigned char *,size_t)': cannot convert argument 1 from 'const _Elem *' to 'const unsigned char *'
Code snippet:
string Base64_decode(const void* data, const size_t len);
string Base64_encode(const unsigned char* src, size_t len);
int main(int argc, char* argv[])
{
string lsOriginal;
string lsEncoded;
string lsDecoded;
lsEncoded = Base64_encode(lsOriginal.c_str(), lsOriginal.size());
lsDecoded = Base64_decode(lsBase64.c_str(), lsBase64.size());
I tried using reinterpret_cast but I couldn't get it to work. I've never used it before so I'm struggling to get it to compile.
Solution 1:[1]
The problem is that std::string::c_str returns a const char* and your function Base64_encode takes an const unsigned char*but there is no implicit conversion from a const char* to const unsigned char*.
To solve this you could use reinterpret_cast as shown below:
Base64_encode(reinterpret_cast<const unsigned char *>(lsOriginal.c_str()), lsOriginal.size());
You can even change the functions to so that their first parameter is a const std::string&. Then there will be no need to have the second parameter corresponding to size since we can use std::string::size member function.
//------------------------vvvvvvvvvvvvvvvvvv------------------->first parameter is lvalue reference to const std::string
std::string Base64_encode(const std::string& src)
//----------------------------------------------^-------------->no need for having second parameter
{
return "fd";//return something
}
int main(int argc, char* argv[])
{
std::string lsOriginal = "fdfd";
std::string lsEncoded;
//--------------------------vvvvvvvvv---------------------->pass the original string by reference
lsEncoded = Base64_encode(lsOriginal);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
