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

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

 

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

DWORD g_dwAttachedProcesses = 0L; // # of attached processes DWORD g_dwPageSize = 0L; // System page size HINSTANCE g_hInstance = 0L; // Instance Handle LONG g_cLock = 0L; // # of outstanding objects BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { BOOL fRetVal = FALSE; SYSTEM_INFO SystemInformation; switch(ul_reason_for_call) { case DLL_PROCESS_ATTACH: // Assume successfully initialized fRetVal = TRUE; // Do one-time initialization when first process attaches if(!g_dwAttachedProcesses) { g_hInstance = (HINSTANCE)hModule; // Get the system page size if(!g_dwPageSize) { GetSystemInfo( &SystemInformation ); // can't fail g_dwPageSize = SystemInformation.dwPageSize; } } // Do per-process initialization here... // Remember that another process successfully attached g_dwAttachedProcesses++; break; case DLL_THREAD_ATTACH: // Clean up when the last process is going away if(g_dwAttachedProcesses == 1) { } // Do per-process clean up here... // Remember that a process has detached g_dwAttachedProcesses--; break; case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return fRetVal; }  

 

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

LIBRARY "mycom" EXPORTS ; EntryName [=InternalName] [@Ordinal] [NONAME] [CONSTANT] ; This is the entry point that DllMainCRTStartup calls DllMain @12 ; Standard OLE exports DllGetClassObject PRIVATE DllCanUnloadNow PRIVATE ; For self-registration. DllRegisterServer PRIVATE DllUnregisterServer PRIVATE  

 

DllMain 函数可以不导出。

 

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

 

STDAPI DllUnregisterServer(void) { return S_OK; } STDAPI DllRegisterServer(void) { return S_OK; } STDAPI DllCanUnloadNow(void) { if(!g_cLock) return S_OK; return S_FALSE; } STDAPI DllGetClassObject(REFCLSID rclsid ,REFIID riid,void **ppv) { return CLASS_E_CLASSNOTAVAILABLE; }

 

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

 

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