DELETE THIS, DLL Export Class and How to Write Plugins (Part II)

zhaozj2021-02-08  210

2. Several methods of derived classes in DLL. In fact, I will know two kinds, please also ask you to add. See how M $ usage is read first. Struct exports {__ decspec (DLLEXPORT) exports (); __ decspec (dllexport) ~ exports ();}; exports :: ~ exports () {} exports :: ~ exports () {} advantage: Complete and local class is used, you can Direct NEW / Delete. Disadvantages: Only automatic connection (that is, LIB), the degree of freedom is not high. You cannot convert the plugin by selecting the DLL (can be implemented by replacing the DLL file, but it is not guaranteed that there is no way to call the subclass function through the same interface after inheriting the same interface. (Because you will always get the parent class unless you recompile the original main program) another method: this declaration exports class:; // exports.hstruct exports {Friend Exports * CreateExports (LPVOID LPPARM); Virtual Int AddRef () Virtual int release (); //, the method, if you don't know, see the first delete thisvirtual do_sth () = 0; // All member functions are virtual functions, the base class can be pure. protected: exports () {} virtual ~ exports () {}} Exports () The CreateExports function is the output function of the DLL. Compile EXPORTS.CPP into exports.dll and then in main.cpp: #include "windows.h" #include "exports.h" void main () {loadingLibrary ("exports"); .... pcreateexports = getProcaddress ("CreateExports" "....); ... exports * pex = pcreateexports (null); pex-> do_sth (); pex-> release ();} Q: Why use protected constructor. A: Because I don't want the Exports class to be used directly (so there is no way to implement the polymorphism, because NEW is less than the subclass), so protected it constructor. This can only get a pointer to the Exports class in the program. The class returned by CreateExports is determined by LPPARM, so that polymorphism is achieved.

Q: Why use the method of delete this (addref / release). A: Because the Exports class is out of New from the DLL, it must be delete in the DLL, so use this method, otherwise it will be released.

Q: Why all member functions are virtual functions. A: If it is not a virtual function, the member function will be connected to the code to .exe, this is not the function of the DLL, so there is no originality. The virtual function is called by the function pointer. The Exports class is still in the DLL, so it can guarantee that the virtual function is inside CALL to the DLL, and .exe only needs the DLL header file to compile the connection.

If there is any shortcomings, mistakes and omissions, please advise

转载请注明原文地址:https://www.9cbs.com/read-1981.html

New Post(0)