954,206 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

passing in ascii/unicode strings to LoadLibrary

hi,

i have this code:

HINSTANCE hComponent = ::LoadLibrary("Component1.dll");

i get this compile error:

Error 1 error C2664: 'LoadLibraryW' : cannot convert parameter 1 from 'const char [15]' to 'LPCWSTR' c:\Documents and Settings\Administrator\Desktop\Component1\Client1\Client1.cpp 9

so i changed the code: HINSTANCE hComponent = ::LoadLibrary((LPCWSTR)"Component1.dll");

however GetLastError returns ERROR_MODULE_NOT_FOUND. the dll IS in the exe directory though, so its not the location that is the problem. in addition, if i call LoadLibraryA, the function loads the library successfully.

so why is LoadLibrary((LPCWSTR)"Component1.dll"); failing?

thanks!

unclepauly
Light Poster
42 posts since Dec 2006
Reputation Points: 16
Solved Threads: 0
 

Use the conversion macros (for ASCII/UNICODE compatibility), not indiscriminate casting to make the compiler STFU.

::LoadLibrary( TEXT("Component1.dll") );

Just because you managed to silence your compiler is in no way a measure of run-time success.

Salem
Posting Sage
Team Colleague
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
 

thats great thank you.

unclepauly
Light Poster
42 posts since Dec 2006
Reputation Points: 16
Solved Threads: 0
 

Hi, It's better to make it more dynamic. For example you have a code like that:

void loadMyDllFile( const char * filename )
{
    ::LoadLibrary( filename ) //it's not working....
}


You have an option to change your compiler mode from UNICODE to MULTIBYTE.
Just go to the project property in visual studio and change the value of Character Set from "use Unicode character set" to "use Multi-Byte character set".

if the compiler gives you an error again, it means that you are using a header file that actually modify the LoadLibrary. To fix that issue just use LoadLibraryA() instead.

Hope it helps,
memphis

memphis.ray
Newbie Poster
2 posts since Sep 2010
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You