Sign in to follow this  
chadsxe

How do you convert 'const TCHAR *' to 'LPWSTR'

Recommended Posts

Ughh...I learned this before but I for the life can figure this out. 'CWaveFile::Open' : cannot convert parameter 1 from 'const TCHAR *' to 'LPWSTR' Long story short the program has a standard of passing const TCHAR*. But somep outside functionality is being added in that has a few functions that except LPWSTR. For example
bool E_XAudio2::LoadFile(const TCHAR *Filename){
    //Read in the wave file
    CWaveFile wav;
    if(FAILED(wav.Open(Filename,NULL,WAVEFILE_READ)))
		return false;}
Any help with be greatly appreciated Regards Chad

Share this post


Link to post
Share on other sites
Since you are working with a TCHAR and need it to be a LPWSTR, you will have two cases to handle: 1.) the TCHAR is a a multibyte string, to which you have to convert into unicode or 2.) the TCHAR is a unicode string and it is ready to be used as a LPWSTR. Here's an example that I think should do what you need it to:


int result = 0;
#ifdef _UNICODE
// Filename is already a LPWSTR, so it is safe to just type cast the pointer
result = FAILED(wav.Open((LPWSTR)Filename,NULL,WAVEFILE_READ));
#else
// Filename is a multibyte character, so we have to convert to a wide character string
size_t length = _tcslen(ptr); // Get the length of the file name
wchar_t * wideFilename = new wchar_t[length + 1]; // New memory for the wide string
memset(wideFilename, 0, sizeof(wchar_t) * (length + 1)); // 0's out memory
mbstowcs(wideFilename, (const char*)Filename, length); // Convert, might need to check the return value
result = FAILED(wav.Open(wideFilename,NULL,WAVEFILE_READ)); // Store the result, since we need to free memory
delete [] wideFilename; // Cleanup memory
#endif
// Regular processing
if(result)
return false;




When _UNICODE is defined, your TCHARs are wchar_t's. This means, the filename is already a unicode string and you can typecast the pointer and pass it to the function.

When _UNICODE is not defined, your TCHAR is a char. You have to explicity convert the char * string into a unicode string. I choose to use mbstowcs, but there are Windows API functions as well you can use that let you set more options.

Hope that makes sense!

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this