Ben
Ben

Reputation: 1349

How do I assign a value to TCHAR* without using a string literal with TEXT()?

I need to assign a value to a TCHAR* variable in C++ and I have been told that this is accomplished using the TEXT() macro. However, I have found that I am only able to do this when using string literals.

//This assignment uses a string literal and works
TCHAR* name = TEXT("example");

//This assignment uses a local variable and causes an error
char* example = "example";
TCHAR* otherName = TEXT(example);

This wouldn't be a problem if it wasn't for the fact that the value of the TEXT() quote parameter will be determined by the user at runtime. Therefore, I need to store the value in some kind of local variable and pass it to the TEXT() macro. How am I able to use a local variable with TEXT() instead of a string literal? Or is there another way that I can assign the value to the TCHAR* varible?

Upvotes: 1

Views: 4701

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 597215

The TEXT() macro only works for literals at compile-time. For non-literal data, you have to perform a runtime conversion instead.

If UNICODE is defined for the project, TCHAR will map to wchar_t, and you will have to use MultiByteToWideChar() (or equivalent) to convert your char* value to a wchar_t buffer:

char* example = "example";
int example_len = strlen(example);
int otherName_len = MultiByteToWideChar(CP_ACP, 0, example, example_len, NULL, 0);
TCHAR* otherName = new TCHAR[otherName_len+1];
MultiByteToWideChar(CP_ACP, 0, example, example_len, otherName, otherName_len);
otherName[otherName_len] = 0;
// use otherName as needed ...
delete[] otherName;

If UNICODE is not defined, TCHAR will map to char instead, and you can just assign your char* directly:

char* example = "example";
TCHAR* otherName = example;

I would suggest using C++ strings to help you:

std::basic_string<TCHAR> toTCHAR(const std::string &s)
{
    #ifdef UNICODE
    std::basic_string<TCHAR> result;
    int len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), s.length(), NULL, 0);
    if (len > 0)
    {
        result.resize(len);
        MultiByteToWideChar(CP_ACP, 0, s.c_str(), s.length(), &result[0], len);
    }
    return result;
    #else
    return s;
    #endif
}

char* example = "example";
std::basic_string<TCHAR> otherName = toTCHAR(example);

Upvotes: 3

Related Questions