Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

How to transform const wchar_t type to LPTSTR (C++)

I am trying to modify an old plugin to create a new one (in C++ and Visual Studio 2019). When I compile I get the following error marking TEXT in red.

E0144: A value of type "const wchar_t *" cannot be used to initialize an entity of type LPTSTR

LPTSTR process_name = TEXT("rFactor2.exe");
module_address = GetModuleBase(process_name, pID);

I investigated and saw a similar post suggesting this:

LPTSTR process_name = foo(TEXT("rFactor2.exe"));

And now I get the following error:

E0020: identifier "foo" is not defined

Could someone tell me how can I create the variable in LPTSTR format (it's the type that GetModuleBase expects)?

question from:https://stackoverflow.com/questions/65641326/how-to-transform-const-wchar-t-type-to-lptstr-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

LPTSTR is defined as TCHAR*. What you want is a const pointer. You can use LPCTSTR, which is defined as TCHAR const*:

LPCTSTR process_name = TEXT("rFactor2.exe");

If your function requires a non-const pointer, you can create a copy:

TCHAR process_name[] = TEXT("rFactor2.exe");

Note that life time of the string literal and the array are not the same.


it's the type that GetModuleBase expects

Considering you are working with legacy code, it is possible that your functions take non-const pointers and don't modify them. If you are certain about that and can't go ahead and fix those function signatures to be const-correct, you can use a type cast. Do this only as a last resort:

auto process_name = const_cast<LPTSTR>(TEXT("rFactor2.exe"));

Recommended reading:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...