Solved

converting to and from TCHAR

Posted on 2006-10-23
14
6,272 Views
Last Modified: 2013-12-14
We have a function which has the following signature
SomeFunction(TCHAR* szPassword,TCHAR* szEncryptPwd)
Now we need to pass in a std::string as the first parameter,and convert the second parameter back into a std::string on return.
How is the conversion from std::string to TCHAR* and back to std::string done?
0
Comment
Question by:ranadhir
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 3
  • +3
14 Comments
 
LVL 12

Expert Comment

by:rajeev_devin
ID: 17793736
This way

TCHAR* szPassword = "test";
std::string password = szPassword;
std::string encryptPwd = szEncryptPwd;

SomeFunction(std::string& password,std::string& encryptPwd)
{
}
0
 
LVL 12

Expert Comment

by:rajeev_devin
ID: 17793738
Or,

TCHAR* szPassword = "test";
std::wstring password = szPassword;
std::wstring encryptPwd = szEncryptPwd;

SomeFunction(std::wstring& password,std::wstring& encryptPwd)
{
}
0
 
LVL 12

Accepted Solution

by:
rajeev_devin earned 50 total points
ID: 17793748
Which one to select depends on your project settings.
If your project is UNICODE, then TCHAR* is wchar_t*, else TCHAR*is char*.
std::wstring is for unicode string std::string is for ascii string.
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:ranadhir
ID: 17793794
i think you did not get the question.We cannot change the function interface.So if i pass in std::string it says
cannot convert parameter 1 from 'std::string' to 'TCHAR *'
How do i pass in the std::string?
The project build is not unicode.
0
 
LVL 12

Expert Comment

by:rajeev_devin
ID: 17793815
Got you
std::string password = szPassword;
std::string encryptPwd = szEncryptPwd;

Use password.c_str()
0
 
LVL 20

Expert Comment

by:ikework
ID: 17793839
hi ranadhir,

std::string param1 = "blablabla";
std::string param2 = "blablabla";

// use c_str() member of std::string to convert to char*, which is TCHAR*
// in a non-unicode project, as rajeev said already

SomeFunction( param1.c_str(), param2.c_str() );


// rajeev showed already, how to convert back to std::string

std::string SomeFunction(TCHAR* szPassword,TCHAR* szEncryptPwd)
{
    ....
    // return std::string
    return std::string( szEncryptPwd );
}


hope it helps,
ike
0
 
LVL 20

Expert Comment

by:ikework
ID: 17793843
sorry rajeev, didn't see your last post, when writing mine ... ;-)
0
 
LVL 30

Expert Comment

by:Axter
ID: 17795292
Hi ranadhir,
> Now we need to pass in a std::string as the first parameter,and convert
> the second parameter back into a std::string on return.

If you want to do this so it works when TCHAR is of UNICODE type and when TCHAR is of ANSI type, then you really want to use a template wrapper function, or an overloaded function.

//Overloaded functions
void ConvertToString(const char* Src, std::string &target)
{
    target = Src;
}

void ConvertToString(const wchar_t* Src, std::string &target)
{
  //Use conversion routine here
}

Example usage:

TCHAR* src = _T("Hello World");
std::string Target;

ConvertToString(src, Target);



David Maisonave (Axter)
Cheers!
0
 
LVL 30

Expert Comment

by:Axter
ID: 17795362
Here's implementation for the conversion:


void ConvertToString(const wchar_t* Src, std::string &target)
{
    target.resize(wcslen(Src)+1, 0);
    wcstombs(target.begin(), Src, Src + wcslen(Src));
}
0
 

Author Comment

by:ranadhir
ID: 17796140
Well i had tried that(using c_str member) earlier and i get the error cannot convert const char* to TCHAR*.
Is a simple cast safe?
0
 
LVL 30

Expert Comment

by:Axter
ID: 17796427
>>Is a simple cast safe?

IMHO, cast is never safe, and there are many well known C++ authors that will tell you that.

If you use the ConverToString overloaded functions which I posted, you will not need to cast.

You should not cast with a TCHAR, because a TCHAR can be an ANSI type or UNICODE.
0
 

Author Comment

by:ranadhir
ID: 17801329
i need not cast tot tchar- i am just casting to char* (castign away constness)- and since we would not need to build unicode at any time(definitive) ,this should be fine,right?
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 17801436
>>>> The project build is not unicode.

If you don't intend to go to UNICODE you should change TCHAR to char, LPCTSTR to LPCSTR, LPTSTR to LPSTR and omit all _T and TEXT macros. That "T" stuff is made to easily (??) switch between UNICODE and non-UNICODE but is nonsense if used in an environment that doesn't apply it consequently for all sources...

>>>> How do i pass in the std::string?

if the required argument is a TCHAR* you shouldn't pass a std::string. You would need to make a writeable copy of the internal char array std::string supplies via cstr():

TCHAR* string2TCHARPtr(const std::string& s, int requiredSize)
{    
     const char* psz = s.c_str();
     if (requiredSize <= s.length())
         requiredSize = s.length()+1;
     TCHAR* ptsz = new TCHAR[requiredSize ];
     if (sizeof(TCHAR) == 1)
     {
           strcpy(ptsz, psz);
     }
     else
     {
           mbstowcs(ptsz, psz, requiredSize );
     }
     return ptsz;
}

However, you should check whether you really need a writeable TCHAR* buffer. If not change the argument type to const TCHAR*. If additionally you know for sure that you never will use it with UNICODE strings you simply can pass s.c_str() when a const TCHAR* is required.

>>>> You should not cast with a TCHAR,

... because std::string.c_str() is a pointer to the internal string buffer which might get corrupted if the callee writes to the casted buffer.

>>>> and convert the second parameter back into a std::string on return

std::string TCHARPtr2string(const TCHAR* ptsz)
{
     if (sizeof(TCHAR)==1)
           return ptsz;
     int len = wcslen(ptsz);
     char* psz = new char[2*len + 1];
     wcstombs(psz, ptsz, 2*len + 1);
     std::string s = psz;
     delete [] psz;
     return s;
}

Regards, Alex

0
 
LVL 11

Expert Comment

by:DeepuAbrahamK
ID: 17954756
Hi,

Maccros like A2T() & T2A() can also do the trick.

Best Regards,
DeepuAbrahamK
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: SunnyDark
This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
The viewer will learn how to use NetBeans IDE 8.0 for Windows to connect to a MySQL database. Open Services Panel: Create a new connection using New Connection Wizard: Create a test database called eetutorial: Create a new test tabel called ee…
The viewer will learn how to use and create keystrokes in Netbeans IDE 8.0 for Windows.

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question