现在的位置: 首页 > 综合 > 正文

COM组件开发实践(六)—From C++ to COM :Part 3

2012年04月01日 ⁄ 综合 ⁄ 共 10305字 ⁄ 字号 评论关闭

     在上一篇文章《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实现两个引出函数DllRegisterServerDllUnregisterServer

1,修改接口文件

      1)将IDBIUnknown派生,删除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)CDBSrvFactoryIDBSrvFactory派生改为由IClassFactory派生。将CDBSrvFactory::CreateDB改为CDBSrvFactory:: CreateInstance,并添加一个成员函数CDBSrvFactory:: LockServer。为CDBCDBSrvFactory都添加一个引用计数变量:ULONG m_dwRefCount;声明一个外部变量:extern ULONG g_dwRefCount;;为CDBCDBSrvFactory加上QueryInterface AddRefRelease三个成员函数

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,实现CDBQueryInterfaceAddRefRelease三个成员函数。

CDB实现文件

注:头文件中成员函数的声明顺序不影响vtable中的顺序,因为vtable是按照IDB的声明顺序来定义的。

3)删除IID_IDBSrvFactory定义;定义全局变量g_dwRefCount;在构造函数中将m_dwRefCount初始化为0;实现CDBSrvFactoryQueryInterfaceAddRefRelease三个成员函数;将CDBSrvFactoryCreateDB函数修改为CreateInstance;实现CDBSrvFactory:: LockServer;添加 DllCanUnloadNow, DllUnregisterServer, DllRegisterServer三个成员函数。

CDBSrvFactory实现

4)修改DEF文件,现在我们需要在db.def中引出DllCanUnloadNowDllRegisterServerDllUnregisterServer三个函数,如下所示:

EXPORTS
          
;WEP @1 RESIDENTNAME
                    DllGetClassObject
                    DllCanUnloadNow
                    DllRegisterServer
                    DllUnregisterServer

5)创建并注册DLL,编译生成DB.dll,在命令行中运行regsvr32dll进行注册。

3,修改客户程序

1)DBDoc.cpp中定义IID_IDB,并且删除以前定义的IID_IDBSrvFactory:

// {30DF3430-0266-11cf-BAA6-00AA003E0EED}
static const GUID CLSID_DBSAMPLE =
0x30df34300x2660x11cf, { 0xba0xa60x00xaa0x00x3e0xe0xed } };
// {30DF3432-0266-11cf-BAA6-00AA003E0EED}
static const GUID IID_IDB =
0x30df34320x2660x11cf, { 0xba0xa60x00xaa0x00x3e0xe0xed } };

     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对象了。

抱歉!评论已关闭.