//========================================================================
//TITLE:
// COM宏小结
//AUTHOR:
// norains
//DATE:
// Wednesday 24-October-2007
//Environment:
// EVC4.0 + Windows CE 5.0 Standard SDK
//========================================================================
COM接口用到的宏主要有六个:STDMETHOD,STDMETHODIMP,STDMETHOD_,STDMETHODIMP_,SUCCEEDED,FAILED.
我们首先来看看这六个宏的定义:
STDMETHOD:
#define STDMETHOD(method) virtual HRESULT STDMETHODCALLTYPE method
#ifdef _WIN32 // Win32 doesn't support __export
#define STDMETHODCALLTYPE __stdcall
#else
#define STDMETHODCALLTYPE __export __stdcall
#endif
STDMETHODIMP:
#define STDMETHODIMP HRESULT STDMETHODCALLTYPE
#ifdef _WIN32 // Win32 doesn't support __export
#define STDMETHODCALLTYPE __stdcall
#else
#define STDMETHODCALLTYPE __export __stdcall
#endif
STDMETHOD_:
#define STDMETHOD_(type,method) virtual type STDMETHODCALLTYPE method
#ifdef _WIN32 // Win32 doesn't support __export
#define STDMETHODCALLTYPE __stdcall
#else
#define STDMETHODCALLTYPE __export __stdcall
#endif
STDMETHODIMP_:
#define STDMETHODIMP_(type) type STDMETHODCALLTYPE
#ifdef _WIN32 // Win32 doesn't support __export
#define STDMETHODCALLTYPE __stdcall
#else
#define STDMETHODCALLTYPE __export __stdcall
#endif
SUCCEEDED:
#define SUCCEEDED(Status) ((HRESULT)(Status) >= 0)
FAILED:
#define FAILED(Status) ((HRESULT)(Status)<0)
由定义我们可以看出两点:
1)STDMETHOD和STDMETHODIMP,STDMETHOD_和STDMETHODIMP_分别为一对,SUCCEEDED和FAILED为相反.
2)STDMETHOD只是STDMETHOD_的简化版.
比如这两个语句互为等价关系:
STDMETHOD (QueryInterface) (REFIID riid, LPVOID * ppv);
STDMETHOD_ (HRESULT,QueryInterface) (REFIID riid, LPVOID * ppv);
既然有STDMETHOD,也有STDMETHODIMP,那么应该在什么情况下使用其中一个呢?
如果继承的函数的声明和定义都在类内定义,则只需使用STDMETHOD即可,如:
//////////////////////////////////////////////
//Browser.h
//////////////////////////////////////////////
class CBrowser:public IOleContainer
{
...
STDMETHOD(LockContainer)(BOOL){return OK;}
}
如果函数的定义在外部,那么声明采用STDMETHOD,定义时使用STDMETHODIMP
//////////////////////////////////////////////
//Browser.h
//////////////////////////////////////////////
class CBrowser:public IOleContainer
{
...
STDMETHOD(LockContainer)(BOOL);
}
//////////////////////////////////////////////
//Browser.cpp
//////////////////////////////////////////////
STDMETHODIMP CBrowser::LockContainer(BOOL)
{
return S_OK;
}
如果将定义的STDMETHODIMP改为声明的STDMETHOD,则编译出错.同样的情况也出现于STDMETHOD_和STDMETHODIMP_.