// --------------
// DLLInterface.h
// --------------
#ifndef __DLLINTERFACE_H__
#define __DLLINTERFACE_H__
// Can't believe vc doesn't automate this kind of stuff
#ifdef __DO_DLL_EXPORT__
#define __DLL_FUNCTION__ __declspec(dllexport)
#else
#define __DLL_FUNCTION__ __declspec(dllimport)
#endif
// Interface that the app provides to the DLL
class IAppInterface
{
public:
virtual int Operation(int parm) = 0;
// ...
};
// Interface that the DLL provides to the app;
class IDLLInterface
{
public:
virtual void MyDLLFunction(int parm) = 0;
// ...
};
extern "C" __DLL_FUNCTION__ IDLLInterface *CreateDLLInterface(IAppInterface *pApp);
typedef IDLLInterface *(*FuncCreateDLLInterface) (IAppInterface *pApp);
#endif //__DLLINTERFACE_H__
// --------------
// DLL.cpp
// This is compiled as a DLL
// --------------
#include <windows.h>
#include <stdio.h>
#define __DO_DLL_EXPORT__
#include "DLLInterface.h"
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
{
return TRUE;
}
// Actual funcionality provided by the DLL.
class CDLLImplementation: public IDLLInterface
{
IAppInterface *m_pApp;
public:
CDLLImplementation(IAppInterface *pApp): m_pApp(pApp) { }
void MyDLLFunction(int parm) { printf("Yes, %d\n", m_pApp->Operation(parm)); }
// ...
};
IDLLInterface *CreateDLLInterface(IAppInterface *pApp)
{
static CDLLImplementation dllImpl(pApp);
return &dllImpl;
}
// --------------
// App.cpp
// This is compiled as an EXE
// --------------
#include <windows.h>
#include "DLLInterface.h"
// Actual funcionality provided by the app.
class CAppImplementation: public IAppInterface
{
public:
int Operation(int parm) { return parm*2; }
};
void main()
{
HMODULE hDLL = ::LoadLibrary("DLL");
FuncCreateDLLInterface createFunc = (FuncCreateDLLInterface)::GetProcAddress(hDLL, "CreateDLLInterface");
CAppImplementation App;
IDLLInterface *pDLL = createFunc(&App);
pDLL->MyDLLFunction(10); //Calls the DLL, which in turn calls the app back.
}
|