Go back to Richel Bilderbeek's homepage.
Go back to Richel Bilderbeek's C++ page.
One of the two ways to call a DLL, the other way is to call a statically loaded DLL.
In the two equivalent examples below, the function GetAnswerOfLife is called from the file ProjectDll.DLL and its answer (which should be 42) is checked.
My favorite and more exception safe solution.
#include <windows.h>
struct DllHandle
{
DllHandle(const char * const filename)
: h(LoadLibrary(filename)) {}
~DllHandle() { if (h) FreeLibrary(h); }
const HINSTANCE Get() const { return h; }
HINSTANCE h;
};
{
//Obtain a handle to the DLL
const DllHandle h("ProjectDll.DLL");
if (!h.Get())
{
MessageBox(0,"Could not load DLL","UnitCallDll",MB_OK);
return 1;
}
//Obtain a handle to the GetAnswerOfLife function
typedef const int (*GetAnswerOfLifeFunction)();
const GetAnswerOfLifeFunction AnswerOfLife
= reinterpret_cast<GetAnswerOfLifeFunction>(
GetProcAddress(h.Get(),"_GetAnswerOfLife"));
if (!AnswerOfLife) //No handle obtained
{
MessageBox(0,"Loading AnswerOfLife failed","UnitCallDll",MB_OK);
return 1;
}
if (AnswerOfLife() != 42)
{
MessageBox(0,"Function AnswerOfLife failed","UnitCallDll",MB_OK);
return 1;
}
{
MessageBox(0,"Function AnswerOfLife successful!","UnitCallDll",MB_OK);
}
}
When you look at the GetProcAddress function, you'll note that C++ Builder add a leading underscore in the function name.
* View this code in plain text.
* Download the project with this example (zip).
#include <windows.h>
{
//Obtain a handle to the DLL
const HINSTANCE dllHandle = LoadLibrary("ProjectDll.DLL");
if (!dllHandle)
{
MessageBox(0,"Could not load DLL","UnitCallDll",MB_OK);
return 1;
}
//Obtain a handle to the GetAnswerOfLife function
typedef const int (*GetAnswerOfLifeFunction)();
const GetAnswerOfLifeFunction AnswerOfLife
= reinterpret_cast<GetAnswerOfLifeFunction>(
GetProcAddress(dllHandle,"_GetAnswerOfLife"));
if (!AnswerOfLife) //No handle obtained
{
MessageBox(0,"Loading AnswerOfLife failed","UnitCallDll",MB_OK);
FreeLibrary(dllHandle);
return 1;
}
if (AnswerOfLife() != 42)
{
MessageBox(0,"Function AnswerOfLife failed","UnitCallDll",MB_OK);
FreeLibrary(dllHandle);
return 1;
}
{
MessageBox(0,"Function AnswerOfLife successful!","UnitCallDll",MB_OK);
FreeLibrary(dllHandle);
}
}
When you look at the GetProcAddress function, you'll note that C++ Builder add a leading underscore in the function name.
* View this code in plain text.
* Download the project with this example (zip).
Go back to Richel Bilderbeek's C++ page.
Go back to Richel Bilderbeek's homepage.