Client application (implements the log class):
defs.h
#define MY_DECLSPEC __declspec(dllexport)
Singleton.h
#include <cassert>template<typename T>class MY_DECLSPEC E_Singleton{public: static T* m_Singleton;public: E_Singleton(void) { assert(!m_Singleton); int offset = (int)(T*)1 - (int)(E_Singleton<T>*)(T*)1; m_Singleton = (T*)((int)this + offset); } ~E_Singleton(void) { assert(m_Singleton); m_Singleton = 0; } static T& GetSingleton(void); static T* GetSingletonPtr(void);};
Log.h
#include "Singleton.h"class MY_DECLSPEC E_Log: public E_Singleton <E_Log>{public: static void Init (); void Write (const char *s); static E_Log& GetSingleton (void); static E_Log* GetSingletonPtr (void);};
Log.cpp
#include <cstdio>#include <cstdlib>#include "defs.h"#include "Log.h"template<> E_Log* E_Singleton<E_Log>::m_Singleton = NULL;//Ugly global variable using C-style IOFILE *f = NULL;void E_Log::Init (){ //Create instance assert (!m_Singleton); m_Singleton = new E_Log; //Open file - I don't even bother closing it f = fopen ("LOG.TXT", "wt");}void E_Log::Write (const char *s){ fprintf (f, "%08X: %s\n", m_Singleton, s);}E_Log& E_Log::GetSingleton(void){ assert(m_Singleton); return *m_Singleton;}E_Log* E_Log::GetSingletonPtr(void){ return m_Singleton;}
main.cpp
#include "defs.h"#include "Log.h"#include <windows.h>int main (){ //Begin E_Log::Init (); E_Log::GetSingleton ().Write ("Hello world!"); //Load the library - I don't even bother unloading it HMODULE hlib = LoadLibrary ("../Library/Library.dll"); return 0;}
DLL Library - uses the LIB generated by the client application (via pragma):
defs.h
#define MY_DECLSPEC __declspec(dllimport)
Library.cpp
#include <windows.h>#include "defs.h"#include "../Client/Log.h"#pragma comment (lib, "../Client/Client.lib")BOOL APIENTRY DllMain (HANDLE, DWORD reason, LPVOID){ if (reason == DLL_PROCESS_ATTACH) E_Log::GetSingleton ().Write ("In DLL"); return TRUE;}
Output to LOG.TXT (as expected) is:
00320FE0: Hello world!00320FE0: In DLL
I hope this helps you find the bug in your code.
[Edited by - Kippesoep on May 25, 2005 2:44:49 PM]