在上一篇文章《COM组件开发实践(五)---From C++ to COM :Part 2 》中,我们进展到使用COM库加载C++对象了,这一篇中我们将真正将C++对象变成 COM对象,而在下一篇中我们将为它添加多接口支持。
C++对象变成COM对象
要将一个C++对象变成一个真正的COM对象,只需要如下操作:
1)实现接口的引用计数。因此每个COM对象都需要有两个函数用于管理引用计数:
ULONG AddRef();
ULONG Release();
这两个函数不返回HRESULT,因为它们不可能失败,除非对象已经不存在,而且它们也不需要返回值,因为它们只是简单地加减引用计数。
2)对象允许实现多个接口。假如对象要为不同的客户返回不同的接口,则需要客户告诉对象它需要哪个接口。实际上前面已经运用了一种方法:DllGetClassObject函数的IID参数。如果对象有多个接口,则类工厂对象的CreateDB函数(也就是真正创建对象的函数)应该增加一个参数:接口ID,即IID。
假如我们的DB对象有多个接口,一个接口用于建表,一个用于读写,一个用于获得数据库信息。我们可以让DB对象提供一个接口查询函数,
HRESULT QueryInterface(RIID riid,void** ppObj);
3)类工厂对象使用标准的IClassFactory接口。4)使用_stdcall调用约定。
5)实现DLL动态卸载。DLL的卸载由COM负责,COM查询DLL看是否还在使用,它会调用DLL的引出函数DllCanUnloadNow来判断是否可以卸载DLL.如果客户程序想让COM卸载所有未使用的库,它会调用CoFreeUnusedLibraries函数。
6)实现对象自动注册。只需要DLL实现两个引出函数DllRegisterServer和DllUnregisterServer
1,修改接口文件
1)将IDB由IUnknown派生,删除Release成员函数声明,为IDB所有成员函数添加_stdcall(因为COM对象在win32下采用标准调用约定)。2)删除类工厂IDBSrvFactory声明,因为我们现在要使用标准类工厂接口IClassFactory,同时也删除IID_IDBSrvFactory的声明。3)声明外部变量IID_IDB,
typedef long HRESULT;
#define DEF_EXPORT __declspec(dllexport)
// {30DF3430-0266-11cf-BAA6-00AA003E0EED}
extern const GUID CLSID_DBSAMPLE;
//{ 0x30df3430, 0x266, 0x11cf, { 0xba, 0xa6, 0x0, 0xaa, 0x0, 0x3e, 0xe, 0xed } };
// {30DF3432-0266-11cf-BAA6-00AA003E0EED}
extern const GUID IID_IDB;
//{ 0x30df3432, 0x266, 0x11cf, { 0xba, 0xa6, 0x0, 0xaa, 0x0, 0x3e, 0xe, 0xed } };
class IDB : public IUnknown
{
// Interfaces
public:
// Interface for data access
virtual HRESULT _stdcall Read(short nTable, short nRow, LPWSTR lpszData) =0;
virtual HRESULT _stdcall Write(short nTable, short nRow, LPCWSTR lpszData) =0;
// Interface for database management
virtual HRESULT _stdcall Create(short &nTable, LPCWSTR lpszName) =0;
virtual HRESULT _stdcall Delete(short nTable) =0;
// Interfase para obtenber informacion sobre la base de datos
virtual HRESULT _stdcall GetNumTables(short &nNumTables) =0;
virtual HRESULT _stdcall GetTableName(short nTable, LPWSTR lpszName) =0;
virtual HRESULT _stdcall GetNumRows(short nTable, short &nRows) =0;
//virtual ULONG Release() =0;
};
2,修改对象程序
1)将CDBSrvFactory由IDBSrvFactory派生改为由IClassFactory派生。将CDBSrvFactory::CreateDB改为CDBSrvFactory:: CreateInstance,并添加一个成员函数CDBSrvFactory:: LockServer。为CDB和CDBSrvFactory都添加一个引用计数变量:ULONG m_dwRefCount;声明一个外部变量:extern ULONG g_dwRefCount;;为CDB和CDBSrvFactory加上QueryInterface, AddRef和Release三个成员函数
typedef long HRESULT;
class CDB : public IDB
{
// Interfaces
public:
// Interface for data access
HRESULT _stdcall Read(short nTable, short nRow, LPWSTR lpszData);
HRESULT _stdcall Write(short nTable, short nRow, LPCWSTR lpszData);
// Interface for database management
HRESULT _stdcall Create(short &nTable, LPCWSTR lpszName);
HRESULT _stdcall Delete(short nTable);
// Interfase para obtenber informacion sobre la base de datos
HRESULT _stdcall GetNumTables(short &nNumTables);
HRESULT _stdcall GetTableName(short nTable, LPWSTR lpszName);
HRESULT _stdcall GetNumRows(short nTable, short &nRows);
HRESULT _stdcall QueryInterface(REFIID riid, void** ppObject);
ULONG _stdcall AddRef();
ULONG _stdcall Release();
// Implementation
private:
CPtrArray m_arrTables; // Array of pointers to CStringArray (the "database")
CStringArray m_arrNames; // Array of table names
ULONG m_dwRefCount;
public:
CDB();
~CDB();
};
extern ULONG g_dwRefCount;
class CDBSrvFactory : public IClassFactory
{
// Interface
public:
HRESULT _stdcall QueryInterface(REFIID riid, void** ppObject);
ULONG _stdcall AddRef();
ULONG _stdcall Release();
HRESULT _stdcall CreateInstance(IUnknown *pUnkOuter, REFIID riid, void** ppObject);
HRESULT _stdcall LockServer(BOOL fLock);
// Implementation
private:
ULONG m_dwRefCount;
public:
CDBSrvFactory();
};
2)为IID_IDB定义GUID,在CDB构造函数中将m_dwRefCount初始化为0,实现CDB的QueryInterface,AddRef,Release三个成员函数。
CDB实现文件
CDB::CDB()
{
m_dwRefCount=0;
}
HRESULT CDB::QueryInterface(REFIID riid, void** ppObject)
{
if (riid==IID_IUnknown || riid==IID_IDB)
{
*ppObject=(IDB*) this;
}
else
{
return E_NOINTERFACE;
}
AddRef();
return NO_ERROR;
}
ULONG CDB::AddRef()
{
g_dwRefCount++;
m_dwRefCount++;
return m_dwRefCount;
}
ULONG CDB::Release()
{
g_dwRefCount--;
m_dwRefCount--;
if (m_dwRefCount==0)
{
delete this;
return 0;
}
return m_dwRefCount;
}
注:头文件中成员函数的声明顺序不影响vtable中的顺序,因为vtable是按照IDB的声明顺序来定义的。
3)删除IID_IDBSrvFactory定义;定义全局变量g_dwRefCount;在构造函数中将m_dwRefCount初始化为0;实现CDBSrvFactory的QueryInterface,AddRef,Release三个成员函数;将CDBSrvFactory的CreateDB函数修改为CreateInstance;实现CDBSrvFactory:: LockServer;添加 DllCanUnloadNow, DllUnregisterServer, DllRegisterServer三个成员函数。
CDBSrvFactory实现
ULONG g_dwRefCount=0;
// {30DF3430-0266-11cf-BAA6-00AA003E0EED}
static const GUID CLSID_DBSAMPLE =
{ 0x30df3430, 0x266, 0x11cf, { 0xba, 0xa6, 0x0, 0xaa, 0x0, 0x3e, 0xe, 0xed } };
// Create a new database object and return a pointer to it
HRESULT CDBSrvFactory::CreateInstance(IUnknown *pUnkOuter, REFIID riid, void** ppObject)
{
if (pUnkOuter!=NULL)
{
return CLASS_E_NOAGGREGATION;
}
CDB* pDB=new CDB;
if (FAILED(pDB->QueryInterface(riid, ppObject)))
{
delete pDB;
*ppObject=NULL;
return E_NOINTERFACE;
}
return NO_ERROR;
}
HRESULT CDBSrvFactory::LockServer(BOOL fLock)
{
if (fLock)
{
g_dwRefCount++;
}
else
{
g_dwRefCount--;
}
return NO_ERROR;
}
CDBSrvFactory::CDBSrvFactory()
{
m_dwRefCount=0;
}
HRESULT CDBSrvFactory::QueryInterface(REFIID riid, void** ppObject)
{
if (riid==IID_IUnknown || riid==IID_IClassFactory)
{
*ppObject=(IDB*) this;
}
else
{
return E_NOINTERFACE;
}
AddRef();
return NO_ERROR;
}
ULONG CDBSrvFactory::AddRef()
{
g_dwRefCount++;
m_dwRefCount++;
return m_dwRefCount;
}
ULONG CDBSrvFactory::Release()
{
g_dwRefCount--;
m_dwRefCount--;
if (m_dwRefCount==0)
{
delete this;
return 0;
}
return m_dwRefCount;
}
STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, void** ppObject)
{
if (rclsid==CLSID_DBSAMPLE)
{
CDBSrvFactory *pFactory= new CDBSrvFactory;
if (FAILED(pFactory->QueryInterface(riid, ppObject)))
{
delete pFactory;
*ppObject=NULL;
return E_INVALIDARG;
}
}
else
{
// here you could check for additional CLSID's you DLL may provide
return CLASS_E_CLASSNOTAVAILABLE;
}
return NO_ERROR;
}
HRESULT _stdcall DllCanUnloadNow()
{
if (g_dwRefCount)
{
return S_FALSE;
}
else
{
return S_OK;
}
}
STDAPI DllRegisterServer(void)
{
HKEY hKeyCLSID, hKeyInproc32;
DWORD dwDisposition;
if (RegCreateKeyEx(HKEY_CLASSES_ROOT, _T("CLSID\\{30DF3430-0266-11cf-BAA6-00AA003E0EED}"), NULL, _T(""), REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKeyCLSID, &dwDisposition)!=ERROR_SUCCESS)
{
return E_UNEXPECTED;
}
if (RegSetValueEx(hKeyCLSID, _T(""), NULL, REG_SZ, (BYTE*) _T("DB Sample Server"), sizeof(_T("DB Sample Server")))!=ERROR_SUCCESS)
{
RegCloseKey(hKeyCLSID);
return E_UNEXPECTED;
}
if (RegCreateKeyEx(hKeyCLSID, _T("InprocServer32"), NULL, _T(""), REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKeyInproc32, &dwDisposition)!=ERROR_SUCCESS)
{
RegCloseKey(hKeyCLSID);
return E_UNEXPECTED;
}
HMODULE hModule=GetModuleHandle(_T("DB.DLL"));
if (!hModule)
{
RegCloseKey(hKeyInproc32);
RegCloseKey(hKeyCLSID);
return E_UNEXPECTED;
}
TCHAR szName[MAX_PATH+1];
if (GetModuleFileName(hModule, szName, sizeof(szName))==0)
{
RegCloseKey(hKeyInproc32);
RegCloseKey(hKeyCLSID);
return E_UNEXPECTED;
}
if (RegSetValueEx(hKeyInproc32, _T(""), NULL, REG_SZ, (BYTE*) szName, sizeof(TCHAR)*(lstrlen(szName)+1))!=ERROR_SUCCESS)
{
RegCloseKey(hKeyInproc32);
RegCloseKey(hKeyCLSID);
return E_UNEXPECTED;
}
RegCloseKey(hKeyInproc32);
RegCloseKey(hKeyCLSID);
return NOERROR;
}
STDAPI DllUnregisterServer(void)
{
if (RegDeleteKey(HKEY_CLASSES_ROOT, _T("CLSID\\{30DF3430-0266-11cf-BAA6-00AA003E0EED}\\InprocServer32"))!=ERROR_SUCCESS)
{
return E_UNEXPECTED;
}
if (RegDeleteKey(HKEY_CLASSES_ROOT, _T("CLSID\\{30DF3430-0266-11cf-BAA6-00AA003E0EED}"))!=ERROR_SUCCESS)
{
return E_UNEXPECTED;
}
return NOERROR;
}
4)修改DEF文件,现在我们需要在db.def中引出DllCanUnloadNow,DllRegisterServer,DllUnregisterServer三个函数,如下所示:
EXPORTS
;WEP @1 RESIDENTNAME
DllGetClassObject
DllCanUnloadNow
DllRegisterServer
DllUnregisterServer
5)创建并注册DLL,编译生成DB.dll,在命令行中运行regsvr32对dll进行注册。
3,修改客户程序
1)在DBDoc.cpp中定义IID_IDB,并且删除以前定义的IID_IDBSrvFactory:
// {30DF3430-0266-11cf-BAA6-00AA003E0EED}
static const GUID CLSID_DBSAMPLE =
{ 0x30df3430, 0x266, 0x11cf, { 0xba, 0xa6, 0x0, 0xaa, 0x0, 0x3e, 0xe, 0xed } };
// {30DF3432-0266-11cf-BAA6-00AA003E0EED}
static const GUID IID_IDB =
{ 0x30df3432, 0x266, 0x11cf, { 0xba, 0xa6, 0x0, 0xaa, 0x0, 0x3e, 0xe, 0xed } };
2)以前创建对象的过程使用的是IDBFactory::CreateDB来创建CDB对象的,现在改为IClassFactory:: CreateInstance:
//新建数据库对象
//m_pDB=new CDB;
// create a database object through the exported function & class factory object
IClassFactory *pDBFactory=NULL;
HRESULT hRes;
hRes=CoGetClassObject(CLSID_DBSAMPLE, CLSCTX_SERVER, NULL, IID_IClassFactory, (void**) &pDBFactory);
if (FAILED(hRes))
{
CString csError;
csError.Format(_T("Error %x obtaining class factory for DB Object!"), hRes);
AfxMessageBox(csError);
return FALSE;
}
hRes=pDBFactory->CreateInstance(NULL, IID_IDB, (void**) &m_pDB);
if (FAILED(hRes))
{
CString csError;
csError.Format(_T("Error %x creating DB Object!"), hRes);
AfxMessageBox(csError);
return FALSE;
}
pDBFactory->Release(); // do not need the factory anymore
3)卸载不再使用的对象,通过调用CoFreeUnusedLibraries来确保任何不再使用的COM DLL对象及时卸载。
BOOL CDBApp::OnIdle(LONG lCount)
{
if (CWinApp::OnIdle(lCount))
{
return TRUE;
}
CoFreeUnusedLibraries();
return FALSE;
}
Ok,到此为止,我们已经将一个简单的C++对象真正转变为一个COM对象了。