1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
|
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <iostream>
using namespace std;
typedef int(__stdcall *PFNADD)(int,int);
typedef int(__stdcall *PFNSUBTRACT)(int,int);
typedef int(__stdcall *PFNNEGATE)(int);
typedef int(__stdcall *PFNSET)(int);
typedef int(__stdcall *PFNZERO)();
class DLLWrapper
{
private:
HMODULE m_hMod;
PFNADD m_pfnAdd;
PFNSUBTRACT m_pfnSubtract;
PFNNEGATE m_pfnNegate;
PFNSET m_pfnSet;
PFNZERO m_pfnZero;
public:
DLLWrapper(LPCSTR modulePath = NULL)
: m_hMod(NULL)
, m_pfnAdd(NULL)
, m_pfnSubtract(NULL)
, m_pfnNegate(NULL)
, m_pfnSet(NULL)
, m_pfnZero(NULL)
{
if(NULL != modulePath)
Load(modulePath);
// could throw here, if it fails to load
}
~DLLWrapper()
{
Unload();
}
DWORD Load(LPCSTR modulePath)
{
Unload();
m_hMod = LoadLibraryA(modulePath);
if(NULL == m_hMod)
return GetLastError();
m_pfnAdd = (PFNADD)GetProcAddress(m_hMod, "Test_Add");
if(NULL != m_pfnAdd)
m_pfnSubtract = (PFNSUBTRACT)GetProcAddress(m_hMod, "Test_Subtract");
if(NULL != m_pfnSubtract)
m_pfnNegate = (PFNNEGATE)GetProcAddress(m_hMod, "Test_Negate");
if(NULL != m_pfnNegate)
m_pfnSet = (PFNSET)GetProcAddress(m_hMod, "Test_Set");
if(NULL != m_pfnSet)
m_pfnZero = (PFNZERO)GetProcAddress(m_hMod, "Test_Zero");
if(NULL == m_pfnZero)
{
Unload();
return GetLastError();
}
return NOERROR;
}
DWORD Unload()
{
if(NULL != m_hMod)
FreeLibrary(m_hMod);
m_pfnAdd = NULL;
m_pfnSubtract = NULL;
m_pfnNegate = NULL;
m_pfnSet = NULL;
m_pfnZero = NULL;
return NOERROR;
}
int Add(int lhs, int rhs) const
{
if(NULL == m_pfnAdd)
return 0; // could throw here
return (*m_pfnAdd)(lhs, rhs);
}
int Subtract(int lhs, int rhs) const
{
if(NULL == m_pfnSubtract)
return 0; // could throw here
return (*m_pfnSubtract)(lhs, rhs);
}
int Negate(int val) const
{
if(NULL == m_pfnNegate)
return 0; // could throw here
return (*m_pfnNegate)(val);
}
int Set(int val) const
{
if(NULL == m_pfnSet)
return 0; // could throw here
return (*m_pfnSet)(val);
}
int Zero() const
{
if(NULL == m_pfnZero)
return 0; // could throw here
return (*m_pfnZero)();
}
};
int main()
{
DLLWrapper wrapper("TEST_DLL.dll");
int w = wrapper.Zero();
cout << "Zero -> w = " << w << endl;
int x = wrapper.Set(3);
cout << "Set(3) -> x = " << x << endl;
x = wrapper.Negate(x);
cout << "Negate(x) -> x = " << x << endl;
int y = wrapper.Add(w, x);
cout << "Add(w, x) -> y = " << y << endl;
int z = wrapper.Subtract(y, 2);
cout << "Subtract(y, 2) -> z = " << z << endl;
cout << endl;
cout << "answer = " << z << endl;
cout << endl;
return 0;
}
|