Andreas Hauschild
Andreas Hauschild

Reputation: 598

Type conversion from string to const wchar_t* . Type does not match

Hi i have the following function which i want to call:

uintptr_t GetModuleBaseAddress(DWORD procId, const wchar_t* modName)

Now i want to write a support function which takes a given string and converts it to the target parameter 'const wchar_t* modName'

I have the folloing function:

wchar_t* stringToWchar(std::string s) {
  std::wstring widestr = std::wstring(s.begin(), s.end());
  const wchar_t* widestr = widestr.c_str();
  return widestr;
}

at the return line i get the error: "no suitable conversion function from to exists".

What do i miss here?

In the final result i want to make a call like:

GetModuleBaseAddress(procId, stringToWchar("module.exe"))

Thx.

Upvotes: 0

Views: 356

Answers (1)

john
john

Reputation: 87944

Rewrite your function to return a wstring

std::wstring stringToWchar(std::string s) {
    return std::wstring(s.begin(), s.end());
}

then use it like this

GetModuleBaseAddress(procId, stringToWchar("module.exe").c_str());

Your code was attempting to return a pointer to an object which no longer exists (widestr). You also declared the variable widestr twice, and you attempted to remove the const qualifier.

Don't program with pointers if you can help it. If you need a pointer for some third party API then generate the pointer at the point you call the third party function, not before.

Upvotes: 2

Related Questions