# Simple Conversion Question

## Recommended Posts

Trying to convert a WCHAR to a char *. I've just never dealt with WCHAR's before. assume I have this code char *myName = "blah"; WCHAR wstr[MAX_PATH] = myName; I get this error for obvious reasons: error C2664: 'LoadObjectFromFile' : cannot convert parameter 3 from 'unsigned short *[260]' to 'unsigned short *' thanks ^_^

##### Share on other sites
MultiByteToWideChar() and WideCharToMultiByte() are what you would use (in Windows, at least) to convert back and forth. Here's some code that's just slightly modified from what I've used before:
void LPSTR_To_LPWSTR(LPCSTR str, LPWSTR& wstr){  int StringLength;  int BufferLength;  StringLength = strlen(str);  BufferLength = MultiByteToWideChar(CP_THREAD_ACP, 0, str, StringLength, NULL, 0);  wstr = new WCHAR[BufferLength];  MultiByteToWideChar(CP_THREAD_ACP, 0, str, StringLength, wstr, BufferLength);}void LPWSTR_To_LPSTR(LPCWSTR wstr, LPSTR& str){  int StringLength;  int BufferLength;  StringLength = wcslen(wstr) + 1;  BufferLength = WideCharToMultiByte(CP_THREAD_ACP, 0, wstr, StringLength, NULL, 0, NULL, NULL);  str = new CHAR[BufferLength];  WideCharToMultiByte(CP_THREAD_ACP, 0, wstr, StringLength, str, BufferLength, NULL, NULL);}

I'm sure there are other ways to do this too, such as through the STL with std::string and std::wstring and stuff that I haven't found yet, but this is the only way that I know of at the moment; it gets the job done.

Don't forget to delete the memory when you're done with it. I suppose you could modify the functions to just copy to buffers that already exist, in order to be able to use statically allocated memory instead... That might be more useful.[/edit]