Daily Archive for February 20th, 2008

转帖:Dynamically loading a class from a dll

Original Article on codegear.com
Create the class dll:

1. Create a virtual base class that contains all of the methods you would need to call from the class. This will be the interface your dll class will support.
2. Make the dll class derive from that interface.
3. Include the interface definition in the executable that will use the dll class.
4. Export a function from the dll that will create a new instance of the dll class and return it’s address (I will call this function CreateClassInstance()).

To use the class in your executable:

1. Call LoadLibrary() on the dll that contains the class.
2. Call GetProcAddress() to gain access to the CreateClassInstance() function.
3. Call CreateClassObject() and store the returned address in an interface pointer.


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
/*
 
This example consists of two projects and six source files:
	header files:
	"FooInterface.h" -- definition for IFoo, the base class/interface
	"FooClass.h" -- definition for FooClass, deriving from IFoo
	"DllExports.h" -- dll's exported functions
 
	dll project:
	"DllMain.cpp" -- main cpp file for the dll project
	"FooClass.cpp" -- contains implementation for FooClass
 
	exe project:
	"ExeMain.cpp" -- main cpp file for exe project	
 
*/
 
 
//-------- FooInterface.h --------//
#ifndef FOOINTERFACE_H
#define FOOINTERFACE_H
 
class IFoo
{
public:
	int GetNumber() = 0;
	void SetNumber( int & ) =0;
};
 
#endif	// FOOINTERFACE_H

Continue reading ‘转帖:Dynamically loading a class from a dll’