Click here to Skip to main content
16,004,806 members
Articles / Programming Languages / C++
Article

Loading DLLs made easy

Rate me:
Please Sign up or sign in to vote.
4.66/5 (30 votes)
1 May 2001 316.9K   111   62
How to load dynamic link librarys the easiest way instead of the long way

Introduction

Have you ever got tired of loading Dynamic Link Libraries the long way, with the usual steps LoadLibrary, and GetProcAddress, then you have to check for each function address if they are NULL, and don't mention about casting the function pointer and hard ways that make your brain strain. And wish there was an easier way to get around things? Well this will just do that in a way and is about the easiest way I know of actually

//GetProcAddresses
//Argument1: hLibrary - Handle for the Library Loaded
//Argument2: lpszLibrary - Library to Load
//Argument3: nCount - Number of functions to load
//[Arguments Format]
//Argument4: Function Address - Function address we want to store
//Argument5: Function Name -  Name of the function we want
//[Repeat Format]
//
//Returns: FALSE if failure
//Returns: TRUE if successful
BOOL GetProcAddresses( HINSTANCE *hLibrary, 
    LPCSTR lpszLibrary, INT nCount, ... )
{
    va_list va;
    va_start( va, nCount );

    if ( ( *hLibrary = LoadLibrary( lpszLibrary ) ) 
        != NULL )
    {
        FARPROC * lpfProcFunction = NULL;
        LPSTR lpszFuncName = NULL;
        INT nIdxCount = 0;
        while ( nIdxCount < nCount )
        {
            lpfProcFunction = va_arg( va, FARPROC* );
            lpszFuncName = va_arg( va, LPSTR );
            if ( ( *lpfProcFunction = 
                GetProcAddress( *hLibrary, 
                    lpszFuncName ) ) == NULL )
            {
                lpfProcFunction = NULL;
                return FALSE;
            }
            nIdxCount++;
        }
    }
    else
    {
        va_end( va );
        return FALSE;
    }
    va_end( va );
    return TRUE;
}

So since we now have the main core to this article, lets now look at how to use this with a short sample that was compiled as a Windows console application.

#include <windows.h>

typedef int ( WINAPI *MESSAGEBOX ) 
    ( HWND , LPCSTR, LPCSTR, DWORD );
typedef int ( WINAPI *MESSAGEBOXEX ) 
    ( HWND , LPCSTR, LPCSTR, DWORD , WORD );

void main(void)
{
    MESSAGEBOX lpfMsgBox = NULL;
    MESSAGEBOXEX lpfMsgBoxEx = NULL;
    HINSTANCE hLib;
    if(GetProcAddresses( &hLib, "User32.dll", 2,
        &lpfMsgBox, "MessageBoxA",
        &lpfMsgBoxEx, "MessageBoxExA" ) )
    {
        lpfMsgBox( 0, "Test1", "Test1", MB_OK );
        lpfMsgBoxEx( 0, "Test2", "Test2", MB_OK, 
            MAKELANGID( LANG_ENGLISH, SUBLANG_ENGLISH_US ) );
    }
    if ( hLib != NULL )
        FreeLibrary( hLib );
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionCompiler Error C2365 Pin
Laurie Stearn30-Nov-16 18:20
Laurie Stearn30-Nov-16 18:20 
GeneralMy vote of 3 Pin
Mạnh Lê5-Nov-13 20:33
Mạnh Lê5-Nov-13 20:33 
QuestionLoadLibrary succeeded but GetLastError returns 203 Pin
agak4-Aug-12 0:51
agak4-Aug-12 0:51 
AnswerRe: LoadLibrary succeeded but GetLastError returns 203 Pin
dhamusport2-Jul-14 1:11
dhamusport2-Jul-14 1:11 
SuggestionMaking it unicode safe Pin
Member 822898024-Jan-12 12:33
Member 822898024-Jan-12 12:33 
Questionwhy else? Pin
uur4-Oct-10 0:50
uur4-Oct-10 0:50 
AnswerRe: why else? Pin
Member 822898024-Jan-12 12:42
Member 822898024-Jan-12 12:42 
GeneralRe: why else? Pin
uur24-Jan-12 21:17
uur24-Jan-12 21:17 
Generalmaking dll with matlab Pin
timo9118-Apr-07 5:16
timo9118-Apr-07 5:16 
GeneralCall VC++ DLL in Matlab Pin
Sylvianne14-Jun-06 0:58
Sylvianne14-Jun-06 0:58 
GeneralI am getting runtime error 53 Pin
deva2k17-Apr-06 1:10
deva2k17-Apr-06 1:10 
GeneralRe: I am getting runtime error 53 Pin
Vijayan.S18-Apr-07 2:12
Vijayan.S18-Apr-07 2:12 
GeneralDebugging -DLL Pin
Antonymaharaj7-Mar-06 20:00
Antonymaharaj7-Mar-06 20:00 
QuestionOverride DLLs? Pin
ngoctrongda28-Sep-05 6:45
ngoctrongda28-Sep-05 6:45 
AnswerRe: Override DLLs? Pin
noxmortis12-Aug-08 1:45
noxmortis12-Aug-08 1:45 
GeneralError adding to my project Pin
buho_usp2-Jun-05 5:27
buho_usp2-Jun-05 5:27 
AnswerRe: Error adding to my project Pin
noxmortis12-Aug-08 1:49
noxmortis12-Aug-08 1:49 
GeneralCall VB 6.0 DLL from C Pin
dagwood200517-Sep-04 5:32
dagwood200517-Sep-04 5:32 
I need to call function in a VB 6.0 DLL from Matlab using the most direct route possible.
I have been able to get Matlab to call a C DLL, which calls a C++ DLL, which calls a VB 6.0 DLL. Is their a more direct route (like having the C DLL call the VB DLL)?


Here is the method I am currently using:

VB 6.0

File->New->Active X DLL
Project name: Project1
Class name: Class1
Function name: blah

Public Function blah() As Integer
blah = 99
End Function

MSVC++ 6.0

File->New->Win32 Dynamic-Link Library
Project name:theCppDll
Copy VB 6.0 Project1.dll to working directory of theCppDll project


theCppDll.h

#ifndef _THECPPDLL_H_
#define _THECPPDLL_H_

extern "C" __declspec(dllexport) int blob(void);

#endif


theCppDll.cpp

#include "windows.h"

# import "Project1.dll"
using namespace Project1;

extern "C" __declspec(dllexport) int blob(void)
{
int x;

HRESULT hresult;
CLSID clsid;

CoInitialize(NULL); //initialize COM library
hresult=CLSIDFromProgID(OLESTR("Project1.Class1"), &clsid); //retrieve CLSID of component

_Class1 *t;
hresult=CoCreateInstance(clsid,NULL,CLSCTX_INPROC_SERVER,__uuidof(_Class1),(LPVOID *) &t);
if(FAILED(hresult))
{
return(200);
}

x = t->blah (); //call method

t->Release(); //call method
CoUninitialize(); //Unintialize the COM library

return(x);
}


MSVC 6.0

File->New->Win32 Dynamic-Link Library
Project name:theCppCall
Copy MSVC++ 6.0 theCppDll.dll to working directory of theCppCall project

theCppCall.h
int __stdcall addInts(int x, int y);

theCppCall.def
LIBRARY myCdll
DESCRIPTION 'myC DLL'
EXPORTS
addInts;

theCppCall.c
#include "theCppCall.h"
#include "stdio.h"
#include "windows.h"

typedef UINT (CALLBACK* LPFNDLLFUNC1)(VOID);

int __stdcall addInts(int x, int y)
{
HINSTANCE hLib = LoadLibrary("theCppDll.dll");
LPFNDLLFUNC1 myBlob;
UINT uRetVal;

if(hLib == NULL)
{
printf("Unable to load library");
return (201);
}

myBlob = (LPFNDLLFUNC1)GetProcAddress(hLib, "blob");
if (myBlob == NULL)
{
printf("Unable to load function");
return (202);
}
uRetVal = myBlob();
x = uRetVal;

return (x+y);
}


Matlab 7.0

Copy theCppCall.h and theCppCall.dll into the working directory
>> loadlibrary theCppCall theCppCall.h
>> libfunctions theCppCall –full
>> calllib(‘theCppCall’, ‘addInts’, 2, 3)
>> unloadlibrary theCppCall

Note that this is a totally useless function, but does demonstrate how each program calls a DLL from another program. The addInts program adds 2 arguments, but the first argument is overwritten by the value (99) retrieved from the VB DLL. So the addInts function adds 99 to the second argument.

Matlab calls the addInts function using a MSVC 6.0 DLL
MSVC 6.0 calls the blob function using a MSVC++ 6.0 DLL
MSVC++ 6.0 calls the blah function using a MSVB 6.0 DLL
QuestionHow to link implicitly a foreign DLL Pin
CEERI16-Sep-04 19:53
CEERI16-Sep-04 19:53 
AnswerRe: How to link implicitly a foreign DLL Pin
dagwood200517-Sep-04 5:50
dagwood200517-Sep-04 5:50 
AnswerRe: How to link implicitly a foreign DLL Pin
deva2k17-Apr-06 1:23
deva2k17-Apr-06 1:23 
GeneralDLL project ignores its RGS settings Pin
ccoti26-Jun-04 20:03
ccoti26-Jun-04 20:03 
QuestionRe: DLL project ignores its RGS settings Pin
noxmortis12-Aug-08 4:48
noxmortis12-Aug-08 4:48 
Generalproblem with inpout32.dll Pin
dnqhung10-Jun-04 1:04
dnqhung10-Jun-04 1:04 
GeneralRe: problem with inpout32.dll Pin
noxmortis12-Aug-08 2:03
noxmortis12-Aug-08 2:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.