John Paul Coder
John Paul Coder

Reputation: 313

no suitable conversion function from "std::wstring" to "LPWSTR" exists in C++

By using the below code, I am getting the path "C:\ProgramFiles"

And then appending "\Test\myupdate.exe" to it.

After that I am storing this path in the "pwszTaskTrigger" structure variable like as below:

mcTskInfo.pwszTaskTrigger = strexepath;

But, When storing I am getting a warning message ("no suitable conversion function from "std::wstring" to "LPWSTR" exists"):

Below is the complete Code:

MCTASKINFO mcTskInfo = { 0 };
WCHAR szCommonFiles[MAX_PATH] = { 0 };
lRet = SHGetFolderPathW(NULL, CSIDL_PROGRAM_FILES, NULL, 0, szCommonFiles);
std::wstring strexepath = L"";
    strexepath.append(szCommonFiles);  //szCommonFiles gives the path "C:\\ProgramFiles"
    strexepath.append(ADD_MCUPDTPATH);
    mcTskInfo.pwszTaskTrigger = strexepath;

#define ADD_MCUPDTPATH          L"\\Test\\myupdate.exe"


struct MCTASKINFO
{

LPWSTR pwszTaskTrigger; 

};

Here I should not change the structure variable pwszTaskTrigger from LPWSTR to LPCWSTR. Because this file is the include file.

How can I fix this issue without changing LPWSTR to LPCWSTR?

Upvotes: 2

Views: 4395

Answers (2)

Norbert Willhelm
Norbert Willhelm

Reputation: 2609

Use the following:

mcTskInfo.pwszTaskTrigger=const_cast<wchar_t*>(strexepath.c_str());

You can also use a C-style cast instead of const_cast. Then the line would look like:

mcTskInfo.pwszTaskTrigger = (LPWSTR)strupdatepath.c_str();

Upvotes: 1

Quentin
Quentin

Reputation: 63144

You can use:

mcTskInfo.pwszTaskTrigger = &strexepath[0];

Or, in C++17, be more descriptive and use data:

mcTskInfo.pwszTaskTrigger = strexepath.data();

But make extra sure that nothing writes more than the length of the string through that pointer, nor uses it after strexepath's lifetime has ended.

Upvotes: 1

Related Questions