0

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.

Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41
  • That's not going to work: your std::wstring in stringToWchar is on the stack and is only valid until you leave the function, ditto the c_str pointer. Nor is that the correct character conversion for a non-ASCII string (or possibly non-Latin1). But it also won't compile because you've got two variables called widestr in the function. – Rup Apr 13 '20 at 09:27
  • 2
    Can you do simply `GetModuleBaseAddress(procId, L"module.exe")`? Or is your actual problem more complex? – Yksisarvinen Apr 13 '20 at 09:27
  • its a simple problem i have an input parameter from a console application, but i cant call GetModuleBaseAddress(procId, argv[2]); – Andreas Hauschild Apr 13 '20 at 09:29
  • So use std::wcin if you need wide characters. – Öö Tiib Apr 13 '20 at 09:33
  • 1
    Can you use `wmain` in place of `main`? (The latter has a `wchar_t` type for `argv`.) See [here](https://stackoverflow.com/q/2438049/10871073). – Adrian Mole Apr 13 '20 at 09:34

1 Answers1

2

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.

john
  • 85,011
  • 4
  • 57
  • 81