Recently I made a utilities function like:
// T2CA
#include "ATLCONV.H"
std::string Utils::CString2String(const CString& cString)
{
#if _MSC_VER > 1200
// Convert a TCHAR string to a LPCSTR
// construct a std::string using the LPCSTR input
CT2CA tmp(cString);
std::string strStd (tmp);
#else
// Deprecated in VC2008.
// construct a std::string using the LPCSTR input
std::string strStd (T2CA (cString));
#endif
return strStd;
}
I did several simple tests and it seems to work fine. However, when I search the web I can see that most usages of T2CA in VC6 have a preceding call of
USES_CONVERSION;
Is there anything that I had missed? Should I invoke my function by :
#else
// Deprecated in VC2008.
// construct a std::string using the LPCSTR input
USES_CONVERSION;
std::string strStd (T2CA (cString));
#endif
In ATL 7.0 USES_CONVERSION is not required anymore. Before that you needed to specify the USES_CONVERSION macro or else you'd get compile errors.
Related
I'm trying to make my win32 program interchangeable between character sets (Unicode and Multi-Byte) the macros such as CreateWindowEx() use wchar_t* and char* depending on the set and for my class name I have it stored in a variable in a windowClass Class.
static constexpr const wchar_t* wndClassName = L"windowclass";
at the moment for other functions I've been using macros I have created defined in a header file
#pragma once
#include <sstream>
#ifdef _UNICODE
#define ConstString(constStringIn) (std::wstringstream() << constStringIn).str().c_str() //used as arguments in functions
#define STRINGALIASMACRO wchar_t* //Used as function return tpyes and wndClassName
#endif // _UNICODE
#ifdef _MBCS
#define ConstString(constStringIn) (std::stringstream() << constStringIn).str().c_str()
#define STRINGALIASMACRO char*
#endif // _MBCS
when trying to replace the wchar_t* with STRINGALIASMACRO and ConstString("windowclass") for the wndClassName variable value the error expression must have a constant value
What could I do to fix this and is it good practice to use macros as type definitions and return types instead of e.g typedef wchar_t* STRINGALIAS I did try this and I got a whole bunch of other errors.
The Win32 API (and the C runtime library) already provide their own sets of preprocessor macros for this exact purpose. Look at:
TCHAR/_TCHAR = char or wchar_t
LP(C)TSTR = (const) char* or (const) wchar_t*
TEXT("literal")/_T("literal") = "literal" or L"literal"
TEXT('literal')/_T('literal') = 'literal' or L'literal'
For example:
#pragma once
#include <windows.h>
#define ConstString(constStringIn) TEXT(constStringIn) //used as arguments in functions
typedef LPTSTR STRINGALIASMACRO; //Used as function return tpyes and wndClassName
typedef LPCTSTR CONSTSTRINGALIASMACRO; //Used as function return tpyes and wndClassName
static constexpr CONSTSTRINGALIASMACRO wndClassName = ConstString("windowclass");
Or simply:
static constexpr LPCTSTR wndClassName = TEXT("windowclass");
See the following for more details:
Win32 Data Types
Working With Strings
Generic-Text Mappings in tchar.h
What are TCHAR, WCHAR, LPSTR, LPWSTR, LPCTSTR (etc.)?
I'm trying to define a function like this:
#ifdef _UNICODE
LPCTSTR A2T(const string& str);
#else
#define A2T
#endif
If my project is in Ansi, than A2T(str) is str itself. When my project is in unicode A2T(str) return a LPCTST type
When UNICODE is defined, LPCTSTR is an alias for const wchar_t*, otherwise it is an alias for const char*.
Your current macro returns const wchar_t* for Unicode, but returns std::string for Ansi. That doesn't make sense. You wouldn't be able to use A2T() consistently everywhere LPCTSTR is expected. The code would not even compile for Ansi since a std::string cannot be assigned directly to a char*. For Unicode, the code would compile, but you would have a memory leak since a conversion from std:string to wchar_t* requires a dynamic memory allocation that you have to free eventually.
A better option is to have A2T() return std::wstring for Unicode, and std::string for Ansi:
#ifdef UNICODE
std::wstring A2T(const string& str)
{
std::wstring result;
// do the conversion from Ansi to Unicode as needed...
// MultiByteToWideChar(), std::wstring_convert, etc...
return result;
}
#else
std::string A2T(const string& str)
{
return str;
}
#endif
Alternatively:
std::basic_string<TCHAR> A2T(const string& str)
{
#ifdef UNICODE
std::wstring result;
// do the conversion from Ansi to Unicode as needed...
// MultiByteToWideChar(), std::wstring_convert, etc...
return result;
#else
return str;
#endif
}
Either way, you get the automatic memory management you need after conversion, and you can use A2T() consistently in both Ansi and Unicode (when passing the return value of A2T(str) to a LPCTSTR, you can use A2T(str).c_str()).
Or, you could simply forget writing your own function and just use the existing A2CT() function or CA2CT class that is already available in MFC/ATL:
ATL and MFC String Conversion Macros
According to MSDN:
https://msdn.microsoft.com/en-us/library/windows/desktop/ff381407%28v=vs.85%29.aspx
You can write TCHAR for char or wchar_t depend on compiler MACRO UNICODE
Is there a similar symbol for std::string and std::wstring?
Thanks!
(My VC++ version is 2013)
You could define it yourself:
typedef basic_string<TCHAR, char_traits<TCHAR>, allocator<TCHAR> > tstring;
I did not find one. I wrote one myself in my code like this -
#ifdef UNICODE
#define tstring std::wstring
#else
#define tstring std::string
#endif
You can also tweak a bit by adding the namespace in your stdafx.h
namespace std {
typedef basic_string<TCHAR, char_traits<TCHAR>, allocator<TCHAR> > tstring;
}
I've read that one can use SHGetSpecialFolderPath(); to get the AppData path. However, it returns a TCHAR array. I need to have an std::string.
How can it be converted to an std::string?
Update
I've read that it is possible to use getenv("APPDATA"), but that it is not available in Windows XP. I want to support Windows XP - Windows 10.
The T type means that SHGetSpecialFolderPath is a pair of functions:
SHGetSpecialFolderPathA for Windows ANSI encoded char based text, and
SHGetSpecialFolderPathW for UTF-16 encoded wchar_t based text, Windows' “Unicode”.
The ANSI variant is just a wrapper for the Unicode variant, and it can not logically produce a correct path in all cases.
But this is what you need to use for char based data.
An alternative is to use the wide variant of the function, and use whatever machinery that you're comfortable with to convert the wide text result to a byte-oriented char based encoding of your choice, e.g. UTF-8.
Note that UTF-8 strings can't be used directly to open files etc. via the Windows API, so this approach involves even more conversion just to use the string.
However, I recommend switching over to wide text, in Windows.
For this, define the macro symbol UNICODE before including <windows.h>.
That's also the default in a Visual Studio project.
https://msdn.microsoft.com/en-gb/library/windows/desktop/dd374131%28v=vs.85%29.aspx
#ifdef UNICODE
typedef wchar_t TCHAR;
#else
typedef unsigned char TCHAR;
#endif
Basically you can can convert this array to std::wstring. Converting to std::string is straightforward with std::wstring_convert.
http://en.cppreference.com/w/cpp/locale/wstring_convert
You should use SHGetSpecialFolderPathA() to have the function deal with ANSI characters explicitly.
Then, just convert the array of char to std::string as usual.
/* to have MinGW declare SHGetSpecialFolderPathA() */
#if !defined(_WIN32_IE) || _WIN32_IE < 0x0400
#undef _WIN32_IE
#define _WIN32_IE 0x0400
#endif
#include <shlobj.h>
#include <string>
std::string getPath(int csidl) {
char out[MAX_PATH];
if (SHGetSpecialFolderPathA(NULL, out, csidl, 0)) {
return out;
} else {
return "";
}
}
Typedef String as either std::string or std::wstring depending on your compilation configuration. The following code might be useful:
#ifndef UNICODE
typedef std::string String;
#else
typedef std::wstring String;
#endif
I'm using a library and sends me std::wstring from one of its functions, and another library that requires _TCHAR [] to be sent to it. How can I convert it?
Assuming you're using Unicode build, std::wstring.c_str() is what you need. Note that c_str() guarantees that the string it returns is null-terminated.
e.g.
void func(const wchar_t str[])
{
}
std::wstring src;
func(src.c_str());
If you're using non-Unicode build, you'll need to convert the Unicode string to non Unicode string via WideCharToMultiByte.
As #Zach Saw said, if you build only for Unicode you can get away with std::wstring.c_str(), but conteptually it would be better to define a tstring (a typedef for std::basic_string<TCHAR>) so you can safely use this kind of string flawlessly with all the Windows and library functions which expect TCHARs1.
For additional fun you should define also all the other string-related C++ facilities for TCHARs, and create conversion functions std::string/std::wstring <=> tstring.
Fortunately, this work has already been done; see here and here.
Actually no compiled library function can really expect a TCHAR *, since TCHARs are resolved as chars or wchar_ts at compile time, but you got the idea.
Use the ATL and MFC String Conversion Macros. This works regardless of whether you are compiling in _UNICODE or ANSI mode.
You can use these macros even if you aren’t using MFC. Just include the two ATL headers shown in this example:
#include <string>
#include <Windows.h>
#include <AtlBase.h>
#include <AtlConv.h>
int main()
{
std::wstring myString = L"Hello, World!";
// Here is an ATL string conversion macro:
CW2T pszT(myString.c_str());
// pszT is now an object which can be used anywhere a `const TCHAR*`
// is required. For example:
::MessageBox(NULL, pszT, _T("Test MessageBox"), MB_OK);
return 0;
}