C++ COM实现之一 创建一个DLL

COM是一种接口技术,它提供了一种方法用于客户程序进行调用。COM原理和技术的文章已经很多了,就不过多讲解了,这里只注重实现。下面分几步对进程内COM组件进行编码实现以达到对实现一个COM的清晰的认识,目的是通过COM接口方法调用DLL中的函数。

首先,创建一个标准的win32 DLL项目mycom,dllmain入口实现如下

 

01.DWORD g_dwAttachedProcesses = 0L; // # of attached processes 02.DWORD g_dwPageSize = 0L; // System page size 03.HINSTANCE g_hInstance = 0L; // Instance Handle 04.LONG g_cLock = 0L; // # of outstanding objects 05.BOOL APIENTRY DllMain( HMODULE hModule, 06. DWORD ul_reason_for_call, 07. LPVOID lpReserved 08. ) 09.{ 10. BOOL fRetVal = FALSE; 11. SYSTEM_INFO SystemInformation; 12. switch(ul_reason_for_call) 13. { 14. case DLL_PROCESS_ATTACH: 15. // Assume successfully initialized 16. fRetVal = TRUE; 17. // Do one-time initialization when first process attaches 18. if(!g_dwAttachedProcesses) 19. { 20. g_hInstance = (HINSTANCE)hModule; 21. // Get the system page size 22. if(!g_dwPageSize) 23. { 24. GetSystemInfo( &SystemInformation ); // can't fail 25. g_dwPageSize = SystemInformation.dwPageSize; 26. } 27. } 28. // Do per-process initialization here... 29. 30. // Remember that another process successfully attached 31. g_dwAttachedProcesses++; 32. break; 33. case DLL_THREAD_ATTACH: 34. // Clean up when the last process is going away 35. if(g_dwAttachedProcesses == 1) 36. { 37. } 38. // Do per-process clean up here... 39. // Remember that a process has detached 40. g_dwAttachedProcesses--; 41. break; 42. case DLL_THREAD_DETACH: 43. case DLL_PROCESS_DETACH: 44. break; 45. } 46. return fRetVal; 47.} 本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/zhoujianhei/archive/2010/07/30/5777404.aspx

 

在工程中添加没有mycom.DEF文件用于导出COM接口函数,如下:

 

 01.LIBRARY "mycom" 02.EXPORTS 03.; EntryName [=InternalName] [@Ordinal] [NONAME] [CONSTANT] 04.; This is the entry point that DllMainCRTStartup calls 05.DllMain @12 06.; Standard OLE exports 07.DllGetClassObject PRIVATE 08.DllCanUnloadNow PRIVATE 09.; For self-registration. 10.DllRegisterServer PRIVATE 11.DllUnregisterServer PRIVATE 本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/zhoujianhei/archive/2010/07/30/5777404.aspx

 

DllMain 函数可以不导出。

其次,在mycom.cpp中实现导出函数,如下:

 

01.STDAPI DllUnregisterServer(void) 02.{ 03. return S_OK; 04.} 05.STDAPI DllRegisterServer(void) 06.{ 07. return S_OK; 08.} 09.STDAPI DllCanUnloadNow(void) 10.{ 11. if(!g_cLock) 12. return S_OK; 13. return S_FALSE; 14.} 15.STDAPI DllGetClassObject(REFCLSID rclsid ,REFIID riid,void **ppv) 16.{ 17. return CLASS_E_CLASSNOTAVAILABLE; 18.}

 

通过以上步骤,一个基本的DLL创建完成,这还不能称之为COM,仅仅是一个DLL导出了几个空函数而已。

你可能感兴趣的:(thread,C++,System,dll,initialization,2010)