0

I'm receiving following error:

Debug Assertion Failed!

Expression: string iterators incompatible

When trying to run such a code:

std::string string_Dir(){return ".\\Dir\\";}
std::wstring wstring_Dir=std::wstring(
    string_Dir().begin()
    ,string_Dir().end()
    );
SetDllDirectory(wstring_Dir.c_str());

Does someone know why

BTW: I followed this.

Community
  • 1
  • 1
Megidd
  • 7,089
  • 6
  • 65
  • 142

2 Answers2

2

You are calling string_Dir() twice and then using iterators from different std::string objects to initialize your std::wstring. That is why you are getting an incompatibility error. You must use iterators from the same std::string object, so call string_Dir() once and assign the return value to a variable:

std::string dir = string_Dir();
std::wstring wstring_Dir(dir.begin(), dir.end());
SetDllDirectory(wstring_Dir.c_str());
// or better: SetDllDirectoryW(wstring_Dir.c_str());

That being said, you are not converting from ANSI to UTF-16, so this code will only work correctly if string_Dir() returns a std::string that contains only 7bit ASCII characters. It will fail if the std::string contains any non-ASCII 8bit characters.

There is a simpler solution - you can call SetDllDirectoryA() instead. You don't need the std::wstring, and the OS can do the ANSI-to-UTF16 conversion for you:

SetDllDirectoryA(string_Dir().c_str());
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
1

According to the documentation, the value in the function call is supposed to be LPCTSTR instead of LPCTWSTR.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Jeff S
  • 250
  • 6
  • 13
  • I'm using UNICODE `#ifdef UNICODE #define SetDllDirectory SetDllDirectoryW` – Megidd Apr 30 '15 at 20:43
  • @user4838962 "To compile an application that uses this function, define _WIN32_WINNT as 0x0502 or later." Have you done this as well? – Jeff S Apr 30 '15 at 20:59
  • @user4838962 Also, wouldn't you call `SetDllDirectoryW`instead of `SetDllDirectory` – Jeff S Apr 30 '15 at 21:04
  • 1
    @JeffS: Since `UNICODE` is defined, `SetDllDirectory()` maps to `SetDllDirectoryW()`. But since `std::wstring` is being used, it is better to call `SetDllDirectoryW()` directly and not rely on `TCHAR` mapping at all. – Remy Lebeau Apr 30 '15 at 21:38