Introduction
This article will teach you How to access class object present in exe from explicitly loaded dll using Inheritance and virtual function . Please consult your seniors before using this method.I am not sure about side effects of this method .This article is usefull when you dont want to expose your code to user and want use some class function from user exe in your DLL
Background
Should know how to use and create DLLs ,How to load DLL explicitly
Using the code
Here I am creating abstract class for interface between executable and DLL. User will derive from this class and override the function which he thinks will be used in DLL
class A
{
public:
virtual void who()=0
{
}
};
The following code is used to derive user class from abstract class. You can create .h file for class A or just copy paste class declaration in user code:
#include <windows.h>
#include<iostream>
#include<string.h>
using namespace std;
class A {
public: virtual void who()=0 { }
};
class B:public A
{
public: void who() { cout<<endl<<"Derived class"; }
void what() { cout<<endl<<"nothing"; }
};
Now user need to pass this object pointer to DLL, so we need to create following exported function in DLL which will use base class pointer to take derived class pointer
extern "C" __declspec(dllexport) void setClassPtr(A *tempPtr)
Following code will load DLL and get function address of setClassPtr()
function. User will create object of derived class B and pass it to pointer of class A *tempPtreA
and then tempPtreA
will be passed to the function mySetPtr()
.
typedef void (WINAPIV* SETPTR )( A*);
int main()
{
wchar_t dllname[100]=L"DLLproject.dll";
HMODULE DLL_Handle;
DLL_Handle = LoadLibrary(dllname);
SETPTR mySetPtr = (SETPTR)GetProcAddress(DLL_Handle,"setClassPtr");
A *tempPtreA=new B();
mySetPtr(tempPtreA);
}
Now function setClassPtr()
from DLL will get called. In the function first I am copying tempPtr
to global pointer of class A Aptr
. This is just for demonstration purpose that you can use this pointer anywhere. Now using Aptr
I am calling who()
. If you see output derived class function will get called since who is virtual function. Here DLL doesn't know the definition of derived class, still we are able access its function using base class pointer. You can use similar kind of abstract class for defining interface between DLL and ex 16 A *Aptr;
extern "C" __declspec(dllexport) void setClassPtr(A *tempPtr)
{
Aptr=tempPtr;
Aptr->who();
}
output ::Derived class