开发者

Convert a 'const wchar_t *' to 'unsigned char *'

开发者 https://www.devze.com 2023-04-09 17:15 出处:网络
In C++ is it possible to convert a \'const wch开发者_开发知识库ar_t *\' to \'unsigned char *\'?

In C++ is it possible to convert a 'const wch开发者_开发知识库ar_t *' to 'unsigned char *'?

How can I do that?

wstring dirName;
unsigned char* dirNameA = (unsigned char*)dirName.c_str();

// I am creating a hash from a string
hmac_sha256_init( hash, (unsigned char*)dirName.c_str(), (dirName.length)+1 );


You need to convert character by character. There are functions like wcstombs to do this.


Try using reinterpret_cast. So:

unsigned char * dirNameA = reinterpret_cast<unsigned char *>(dirName.c_str());

That might not work because c_str returns a const wchar_t *so you can also try:

unsigned char * dirNameA = reinterpret_cast<unsigned char *>(
                               const_cast<wchar_t *>(dirName.c_str())
                           );

This works because hmac_sha256_init should accept a binary blob as its input, so the unicode string contained in dirName is an acceptable hash input.

But there's a bug in your code - the length returned by dirName.length() is a count of characters, not a count of bytes. That means that passing too few bytes to hmac_sha256_init since you're passing in a unicode string as a binary blob, so you need to multiply (dirName.length()) by 2.


Since you're using WinAPI, use WideCharToMultiByte.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号