Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LoadLibrary taking a LPCTSTR

I want to develop a plugin system using LoadLibrary.
My problem is: I want my function to take a const char* and LoadLibrary takes a LPCTSTR.
I had the bright idea to do (LPCSTR)path which kept giving me a module not found error.

Current code is below. If I uncomment the widepath = L.. line it works fine. I've read solutions using MFC but I'd like to not use MFC.

Current code:

bool PluginLoader::Load(char *path)
{
    path = "Release\\ExamplePlugin.dll";
    LPCTSTR widepath = (LPCTSTR)path;
    //widepath = L"Release\\ExamplePlugin.dll";

    HMODULE handle = LoadLibrary(widepath);
    if (handle == 0)
    {
        printf("Path: %s\n",widepath );
        printf("Error code: %d\n", GetLastError());

        return false;
    }

    int (*load_callback)() = (int (*)()) GetProcAddress(handle, "_plugin_start@0");

    if (load_callback == 0)
    {
        return false;
    }

    return load_callback() == LOAD_SUCCESS;
}
like image 897
Ben Avatar asked Mar 06 '11 03:03

Ben


People also ask

How does LoadLibrary work?

LoadLibrary can be used to load a library module into the address space of the process and return a handle that can be used in GetProcAddress to get the address of a DLL function. LoadLibrary can also be used to load other executable modules.

Which DLL is LoadLibrary?

Kernel32. dll is loaded into every Windows process, and within it is a useful function called LoadLibrary .


2 Answers

Use LoadLibraryA(), it takes a const char*.

Winapi functions that take strings exist in two versions, an A version that takes a Ansi strings and a W version that takes wide strings. There's a macro for the function name, like LoadLibrary, that expands to either the A or the W, depending if UNICODE is #defined. You are compiling your program with that #define in effect, so you get LoadLibraryW(). Simply cheat and use LoadLibraryA().

like image 54
Hans Passant Avatar answered Sep 19 '22 19:09

Hans Passant


I suggest you using TCHAR and LoadLibrary instead of using manually char or wchar_t and LoadLibraryA or LoadLibraryW to make a generic application, both for UNICODE and ASCII characters.

So you could do:

TCHAR x[100] = TEXT("some text");

I suggest you reading this article. LPCTSTR is a const TCHAR*.

Why use LoadLibrary instead of LoadLibraryW or LoadLibraryA? To support both UNICODE and ASCII without creating two different programs, one to work with char and the other with wchar_t.

Also, take a look at what Microsoft says about it: Conventions for Function Prototypes

like image 21
Oscar Mederos Avatar answered Sep 20 '22 19:09

Oscar Mederos