COM Utility

LiuYinChina發表於2013-02-18
COM 工具類,誰用誰知道!

#ifndef COMUtility_H
#define COMUtility_H
 
//////////////////////////////////////////////////////////////////////////
 
#include <Windows.h>
 
//////////////////////////////////////////////////////////////////////////
 
//  define the prototype of the class factory entry point in a COM dll
typedef HRESULT (STDAPICALLTYPE *DllGetClassObjectT)(REFCLSID clsid, REFIID iid, LPVOID *ppv);
 
//////////////////////////////////////////////////////////////////////////
 
template <DWORD dwUnique>
class COMUtilityT
{
public:
    static HRESULT CreateObjectFromPath(REFCLSID clsid, IUnknown **ppUnk, LPCSTR lpszPath)
    {
        //  load the target DLL directly
        HMODULE hModule = LoadLibraryA(lpszPath);
        if (hModule == NULL) {
            return HRESULT_FROM_WIN32(GetLastError());
        }
 
        return CreateObjectFromPath(hModule, clsid, ppUnk);
    }
    static HRESULT CreateObjectFromPath(REFCLSID clsid, IUnknown **ppUnk, LPCWSTR lpszPath)
    {
        //  load the target DLL directly
        HMODULE hModule = LoadLibraryW(lpszPath);
        if (hModule == NULL) {
            return HRESULT_FROM_WIN32(GetLastError());
        }
 
        return CreateObjectFromPath(hModule, clsid, ppUnk);
    }
 
private:
    static HRESULT CreateObjectFromPath(HMODULE hModule, REFCLSID clsid, IUnknown **ppUnk)
    {
        if (hModule == NULL) {
            return HRESULT_FROM_WIN32(GetLastError());
        }
 
        //  the entry point is an exported function
        DllGetClassObjectT fn = (DllGetClassObjectT) GetProcAddress(hModule, "DllGetClassObject");
        if (fn == NULL) {
            return HRESULT_FROM_WIN32(GetLastError());
        }
 
        //  create a class factory
        CComPtr<IUnknown> pUnknown;
        HRESULT hr = fn(clsid, IID_IUnknown, (LPVOID *) &pUnknown);
        if (SUCCEEDED(hr)) {
            CComQIPtr<IClassFactory> pClassFactory(pUnknown);
            if (pClassFactory == NULL) {
                hr = E_NOINTERFACE;
            }
            else {
                //  ask the class factory to create the object
                hr = pClassFactory->CreateInstance(NULL, IID_IUnknown, (LPVOID *) ppUnk);
            }
        }
        return hr;
    }
};
 
//////////////////////////////////////////////////////////////////////////
 
typedef COMUtilityT<0> COMUtility;
 
//////////////////////////////////////////////////////////////////////////
 
#endif

相關文章