动态链接库

来源:互联网 发布:做软件开发 编辑:程序博客网 时间:2024/05/21 00:15

Abstract: Includes a short explaination and simple example of using virtual base classes as interfaces across an exe and a run-time loaded dll.

 

                Using a class from a dll is easy when the dll is statically (or load-time) linked to your executable. The compiler gets the information it needs from the dll's header and the linker gets all information it needs from the import library. Periodically, someone posts to our newsgroups asking how to newsgroups load a class from a dll completely at run-time. The following is a simple answer to this question, using some of the basic techniques behind COM and CORBA.

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.

Make calls to the object using the interface pointer and these calls will foreward to the derived object. Don't forget to delete the pointer when done with the object.

Depending on the complexity of the applicaiton, you may have to deal with reference counting issues to determine when to delete the pointer you received from the dll. This example does not take these considerations into account.

 
原创粉丝点击