Search code examples
c++wstringlpcwstrsetdlldirectory

Expression: string iterators incompatiable, when calling "SetDllDirectory"


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.


Solution

  • 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());