How to convert tchar pointer to char pointer - mfc

I want to conver a tchar* to char * is this possible . if yes how to do it. I use unicode setting

A TCHAR is either a plain char or a wchar_t depending on your project's settings. If it's the latter, you would need to use WideCharToMultiByte with appropriate code page parameter.

You can't convert the pointer, you need to allocate a new string that is "char" instead of "wchar_t"
the most elegant way to do this is with the ATL conversion macros because it will hide all the allocation and called to the functions mentioned in the other comments
example
#include <atlbase.h>
#include <atlconv.h>
void YourFunction()
{
TCHAR wszHelloTchar = _T("Hello!\n");
USES_CONVERSION; // a macro required once before using T2A() and other ATL macros
// printf require a char*
// T2A converts (if necessary) the TCHAR string to char
printf( T2A( wszHelloTchar ) );
}

I find wcstombs works great for doing this sort of thing,

Related

Am I converting properly from "const char *" to "TCHAR*"?

I'm trying to pass a process name as a TCHAR to the following void:
void GetBaseAddressByName(DWORD pID, TCHAR *pN)
By doing it like this:
GetBaseAddressByName(aProcs[i], (TCHAR*)"Process.exe");
So my question is: is what I am doing correct? Because I have tried both TEXT("Process.exe") and _T("Process.exe") with my project's Character Set both on Multi-Bite and Unicode and it just tells me that
argument of type "const char*" is incompatible with parameter of type "TCHAR*"
The short answer is no. TCHAR maps to either char or wchar_t depending on your project's Unicode/Multi-byte setting. So, in general, a cast like that is either unnecessary or incorrect. The correct way, as you said, is to use either the TEXT or _T macro. The reason you're getting an error is that you're trying to pass a const character string to a function that expects a mutable character string. The safeset way to get around the error is to copy your constant string into a local TCHAR buffer and then pass that to GetBaseAddressByName.
It is better to have a TCHAR array first, then copy into it.
#include "atlstr.h"
char const * procName = "processName.exe";
TCHAR szName [128];
_tcscpy(szName, A2T(procName));
GetBaseAddressByName(aProcs[i], szName);
As suggested by #Remy Lebeau in the comments, procName can be defined as TCHAR const * procName = TEXT("processName.exe");.
(TCHAR*)"Process.exe" is not a valid type-cast. It will "work" when the project charset is set to ANSI/MBCS, but it will produce garbage if the charset is set to Unicode.
Using TEXT("Process.exe") is the correct way to make a string literal use TCHAR characters.
GetBaseAddressByName(aProcs[i], TEXT("Process.exe"));
However, you need to change your pN parameter to const TCHAR * (or LPCTSTR) instead:
void GetBaseAddressByName(DWORD pID, const TCHAR *pN);
void GetBaseAddressByName(DWORD pID, LPCTSTR pN);
A string literal is const data, and you cannot pass a pointer-to-const-data where a pointer-to-non-const-data is expected (without casting the const away with const_cast). That is why you were still getting errors when trying to use the TEXT()/_T() macros.
You need a L, like L"Process.exe". Unicode strings are specified with L"".
That said, there is no reason to use TCHAR. Use unicode all the time, if doing Windows work only.

how to convert char array to LPCTSTR

I have function like this which takes variable number of argument and constructs
the string and passes it to another function to print the log .
logverbose( const char * format, ... )
{
char buffer[1024];
va_list args;
va_start (args, format);
vsprintf (buffer,format, args);
va_end (args);
LOGWriteEntry( "HERE I NEED TO PASS buffer AS LPCTSTR SO HOW TO CONVERT buffer to LPCTSTR??");
}
Instead of using buffer[1024] is there any other way? since log can be bigger or very smaller . All this am writing in C++ code please let me know if there is better way to do this .....
You can probably just pass it:
LOGWriteEntry (buffer);
If you are using ancient memory models with windows, you might have to explicitly cast it:
LOGWriteEntry ((LPCTSTR) buffer);
correction:
LPCTSTr is Long Pointer to a Const TCHAR STRing. (I overlooked the TCHAR) with the first answer.
You'll have to use the MultiByteToWideChar function to copy buffer to another buffer and pass that to the function:
w_char buf2 [1024];
MultiByteToWideChar (CP_ACP, 0, buffer, -1, buf2, sizeof buf2);
LOGWriteEntry (buf2);
A good way to proceed might be from among these alternatives:
Design the logverbose function to use TCHAR rather than char; or
Find out if the logging API provides a char version of LOGWriteEntry, and use that alternative.
If no char version of LOGWriteEntry exists, extend that API by writing one. Perhaps it can be written as a cut-and-paste clone of LOGWriteEntry, with all TCHAR use replaced by char, and lower-level functions replaced by their ASCII equivalents. For example, if LOGWriteEntry happens to call the Windows API function ReportEvent, your LOGWriteEntryA version could call ReportEventA.
Really, in modern applications, you should just forget about char and just use wchar_t everywhere (compatible with Microsoft's WCHAR). Under Unicode builds, TCHAR becomes WCHAR. Even if you don't provide a translated version of your program (all UI elements and help text is English), a program which uses wide characters can at least input, process and output international text, so it is "halfway there".

C++ Combine 2 Tchar

I'm trying to combine 2 tchar.
char username[UNLEN+1];
DWORD username_len = UNLEN+1;
GetUserName(username, &username_len);
TCHAR* appdatapath ="C:\\Users\\"+username+"\\AppData";
But I get error error at appdatapath line. How can I combine 2 tchar? Thanks
Have a look at strcat and wcscat. You can't add char pointer with char array.
If you are on a windows machine, you can use _tcscat which will redirect to the right function to use depending on _UNICODE and _MBCS defines.
Might want to use the safe versions as well by appending _s to the function name.
As pointed in the comments, you can also use snprintf like so:
const size_t concatenated_size = 256;
char concatenated[concatenated_size];
snprintf(concatenated, concatenated_size, "C:\\Users\\%s\\AppData", username);
Since you have string literals before and after the runtime string, it is probably a better approach.
To answer the question in the title: you concatenate two TCHAR strings using the _tcscat function.
However, there are other issues in your code related to this: GetUserName expects a LPTSTR, i.e. a pointer to a buffer TCHAR characters. Furthermore, there's another TCHAR usage in
TCHAR* appdatapath ="C:\\Users\\"+username+"\\AppData";
The issue with this is that the type to which TCHAR expands changes depending on whether _UNICODE is defined. In particular, if you set it, TCHAR (eventually) expands to wchar and hence GetUserName expects a wchar_t* but you pass a char*. Another issue is that you cannot concatenate C arrays using the + operator.
I suggest to stop worrying about TCHAR in the first place and always just compile with _UNICODE defined - and use wchar throughout your code. Also, since you're using C++, just use std::wstring:
wchar username[UNLEN+1];
DWORD username_len = UNLEN+1;
GetUserNameW(username, &username_len);
std::wstring appdatapath = L"C:\\Users\\";
appdatapath += username;
appdatapath += L"\\AppData";
Last but not least: your entire code can probably be replaced with a call to the SHGetSpecialFolderPath function - pass CSIDL_APPDATA to it to get the "AppData" path.
#include <tchar.h>
const size_t stringSize= 20;
TCHAR value[stringSize] = { 0 };
_tcscat_s(value, stringSize, TEXT("appendMe"));
MSDN: _tcscat_s

How to convert std::wstring to a TCHAR*?

How to convert a std::wstring to a TCHAR*? std::wstring.c_str() does not work since it returns a wchar_t*.
How do I get from wchar_t* to TCHAR*, or from std::wstring to TCHAR*?
use this :
wstring str1(L"Hello world");
TCHAR * v1 = (wchar_t *)str1.c_str();
#include <atlconv.h>
TCHAR *dst = W2T(src.c_str());
Will do the right thing in ANSI or Unicode builds.
TCHAR* is defined to be wchar_t* if UNICODE is defined, otherwise it's char*. So your code might look something like this:
wchar_t* src;
TCHAR* result;
#ifdef UNICODE
result = src;
#else
//I think W2A is defined in atlbase.h, and it returns a stack-allocated var.
//If that's not OK, look at the documenation for wcstombs.
result = W2A(src);
#endif
in general this is not possible since wchar_t may not be the same size as TCHAR.
several solutions are already listed for converting between character sets. these can work if the character sets overlap for the range being converted.
I prefer to sidestep the issue entirely wherever possible and use a standard string that is defined on the TCHAR character set as follows:
typedef std::basic_string<TCHAR> tstring;
using this you now have a standard library compatible string that is also compatible with the windows TCHAR macro.
You can use:
wstring ws = L"Testing123";
string s(ws.begin(), ws.end());
// s.c_str() is what you're after
Assuming that you are operating on Windows.
If you are in Unicode build configuration, then TCHAR and wchar_t are the same thing. You might need a cast depending on whether you have /Z set for wchar_t is a type versus wchar_t is a typedef.
If you are in a multibyte build configuration, you need MultiByteToWideChar (and vica versa).

Convert CString to character array?

How to convert CString in MFC to char[] (character array)
You use CString::GetBuffer() to get the TCHAR[] - the pointer to the buffer. If you compiled without UNICODE defined that's enough - TCHAR is same as char, otherwise you'll have to allocate a separate buffer and use WideCharToMultiByte() for conversion.
I struggled with this, but what I use now is this: (UNICODE friendly)
CString strCommand("My Text to send to DLL.");
**
char strPass[256];
strcpy_s( strPass, CStringA(strCommand).GetString() );
**
// CStringA is a non-wide/unicode character version of CString
This will then put your null terminated char array in strPass for you.
Also, if you control the DLL on the other side, specifying your parameters as:
const char* strParameter
rather than
char strParameter*
will "likely" convert CStrings for you with the default casting generally being effective.
You can use GetBuffer function to get the character buffer from CString.
Calling only the GetBuffer method is not sufficient, you'll need too copy this buffer to the array.
For example:
CString sPath(_T("C:\temp\"));
TCHAR tcPath[MAX_PATH];
_tcscpy(szDisplayName, sPath.GetBuffer(MAX_PATH));
As noted elsewhere, if You need to port CString for warning C4840: non-portable f.
The quick, Unicode && Multibyte striong conversion is using:
static_cast
sample:
//was: Str1.Format( szBuffer, m_strName );
Str1.Format(szBuffer, static_cast<LPCTSTR>(m_strName) );