但是在開發時,實際上總是沒這麼美好,註冊DLL其實是很麻煩的,新舊相容性,開發中的版本等等的問題,而走manifest其實可以避開註冊這條路,但是今天我需要寫一個COM module讓別人使用,而這個COM module在AP裡是走manifest的,所以不會被註冊,連帶的module會用到其他的Library也不走註冊這條路,而因為一些其他的原因,也不能將此Library寫入manifest裡,只能尋求其他途徑了。
由於COM的DLL都會link到一些基本的COM Library,所以是有一些export的API可以繞過註冊來create COM instance的,直接參考以下的Sample Code吧。
// {599D2F5F-BA8D-4009-941C-A5393EBD5C58}
DEFINE_GUID(CLSID_MyCOM,
0x599d2f5f, 0xba8d, 0x4009, 0x94, 0x1c, 0xa5, 0x39, 0x3e, 0xbd, 0x5c, 0x58);
// {4C452CB2-469C-4236-AE5C-F48A28EC0870}
DEFINE_GUID(IID_IMyCOM,
0x4c452cb2, 0x469c, 0x4236, 0xae, 0x5c, 0xf4, 0x8a, 0x28, 0xec, 0x8, 0x70);
HRESULT CreateInstance(IMyCOM** pMyCom)
{
HMODULE hDll = LoadLibrary("MY_COM.dll");//Need refine by your self
if(hDll)
{
//////////////////////////////////////////////////////////////////////////
// Initial COM instance without register
// Try to load COM DLL directly, and call DllGetClassObject to get IID_IClassFactory
// And Create COM instance by IID_IClassFactory
// -----------------------------------------------------------------------
// HRESULT hr = CoCreateInstance(CLSID_MyCOM,
// NULL,
// CLSCTX_INPROC_SERVER,
// IID_IMyCOM,
// (PVOID*)&pMyCom);
//////////////////////////////////////////////////////////////////////////
CComPtr<IClassFactory> spFactory;
// Get address of DllGetClassObject exported method
PDLLGETCLSOBJ pDllGetCLSObj = (PDLLGETCLSOBJ)GetProcAddress(hDll, "DllGetClassObject");
// Call DllGetClassObject and get the proper IClassFactory interface
HRESULT hr = pDllGetCLSObj(CLSID_MyCOM, IID_IClassFactory, reinterpret_cast<PVOID*>(&spFactory));
if( FAILED(hr) )
{
printf(__FUNCTION__" [Err] Can't get spFactory hr=%X", hr);
return E_FAIL;
}
// Create an instance of IMyCOM
hr = spFactory->CreateInstance(NULL, IID_IMyCOM, (PVOID*)pMyCom);
if( FAILED(hr) )
{
printf(__FUNCTION__" [Err] Init IMyCOM Fail! hr=%X", hr);
return E_FAIL;
}
}
else
{
return E_FAIL;
}
return S_OK;
}
Reference:
- StackOverflow - Windows/C++: how to use a COM dll which is not registered
沒有留言:
張貼留言