How do you convert from 'const wchar_t *' to 'WCHAR [32]'

Started by
10 comments, last by Codeka 14 years, 5 months ago
Hi, Trying to figure out a conversion. I am passing in a std::wstring refrence to a function and then trying to assign it to a D3DXFONT_DESC member. int CreateFont(std::wstring& name) { D3DXFONT_DESC lf. lf.FaceName = name.ctr(); } This gives error C2440: '=' : cannot convert from 'const wchar_t *' to 'WCHAR [32]' Any suggestions? Regards Chad
Advertisement
You need to memcpy or strcpy the string from name.c_str() to the wchar_t array. Remember that lf.FaceName must be a null terminated string!
Quote:Original post by Fox32
You need to memcpy or strcpy the string from name.c_str() to the wchar_t array. Remember that lf.FaceName must be a null terminated string!


You will probably not want to use strcpy() since it is not designed to handle multibyte strings. memcpy() will not null-terminate for you. According to MSDN the function wcscpy() can be used; it has the same signature as strcpy() but takes widechar arguments.

EDIT: And obviously you need to be careful not to overflow the buffer too. :)
Quote: And obviously you need to be careful not to overflow the buffer too. :)


wcscpy_s would solve this problem.

Edit:

errno_t result = wcscpy_s(lf.FaceName, name.ctr());


If result is non zero, your name is probably longer than 31 characters and than lf.FaceName isn't modified.
Excuse me if I am a dope but I am trying this and it is not working.

int CreateFont(std::wstring& name)
{
D3DXFONT_DESC lf.
assert(fontName.length() < sizeof(lf.FaceName));
strncpy_s(lf.FaceName, sizeof(lf.FaceName), fontName.c_str(), fontName.length() + 1);
}


error C2664: 'errno_t strncpy_s(char *,rsize_t,const char *,rsize_t)' : cannot convert parameter 1 from 'WCHAR [32]' to 'char *'

Regards

Chad


Hmm this seem sto be compiling fine now but I am worried about overflow

int CreateFont(std::wstring& name)
{
D3DXFONT_DESC lf.
assert(fontName.length() < sizeof(lf.FaceName));
wcscpy_s(lf.FaceName, sizeof(lf.FaceName), fontName.c_str());
}

how would you suggest I check for them.

Regards

Chad
Quote:Original post by chadsxe
error C2664: 'errno_t strncpy_s(char *,rsize_t,const char *,rsize_t)' : cannot convert parameter 1 from 'WCHAR [32]' to 'char *'


If you use wide strings, you need to use the wide string version of strncpy_s called wcsncpy_s.

Do you feel like the assert if enough of a check for overflow?

Regards

Chad
That depends on where the string is coming from. If it's chosen by the user, definitely not.
Quote:Original post by SiCrane
That depends on where the string is coming from. If it's chosen by the user, definitely not.


It is chosen by the user. What steps can I take to assure that the user is under or equal to or less then 31 characters.

Regards

Chad

This topic is closed to new replies.

Advertisement