Well, if you mess with DLLs alot, I guess you once wanted to export a class as well as functions.
OK, infact there is a nice trick which is to create an instance of the class in the DLL itself and pass a pointer to the DLL loader.
Now let's get into depth, every function you want to export in the class, you'll have to make it a virtual function, thus, the DLL loader will "find" the code of the function in the virtual table of that instance.
The DLL would be something like this for example:
Class1.cpp: ----------- Class1::Class1() { . // You get the idea . . }
void Class1::SetData(int nx)... void Class1::ShowData()... Class1::~Class1()...
// Now this is the most important function: __declspec(dllexport) Class1* MakeClass1Ptr() {// Return an instance of the Class1, ofcourse don't forget to delete it by yourself! return new Class1; }
Class1.h: --------- class Class1 { private: int x; public: Class1(); virtual void SetData(int nx); virtual void ShowData(); virtual ~Class1(); // Yes, dtor can(and should) be a virtual too! };
Hey, don't forget to export the MakeClass1Ptr function in your DLL's .def file!
Now Loader time: #include "class1.h" // You'll have to include it, in order to know how the class is built!
HMODULE hDLL = LoadLibrary("Class.dll"); // Loading DLL
typedef Class1* (*MakeClass1ptr)(void); MakeClass1ptr ptr = (MakeClass1ptr)GetProcAddress(hDLL, "MakeClass1Ptr"); // Getting a pointer to function
Class1* c1; c1 = ptr(); // Calling the function and getting the pointer to the instance now.
c1->SetData(0xd11c1a77); // Use the virtual functions... c1->ShowData(); // Ditto
delete c1; // Destroy the class
FreeLibrary(hDLL); // Unload DLL
That was all about it... It's a nice trick, there are a few more ways but I chose to show this one, because it's the easiest in my opinion...
VC 6.0 Source Code - http://qsoft.ragestorm.com/tutors/windows/dllclass.zip |