com基础

com,为什么要它?
简单地把C++类定义从dll中引出来"这种方案并不能提供合理的二进制组件结构。因为C++类那既是接口也是实现。这里需要把接口从实现中分离出来才能提供二进制组件结构。此时需要有二个C++类,一个作为接口类另一个作为实现类

COM要求所有的方法都会返回一个HRESULT类型的错误号。HRESULT 其实就一个类型定义: typedef LONG HRESULT;

有关HRESULT的定义见 winerror.h 文件


怎样判断COM调用是否成功?
使用返回值来判断,首先看下,com 的返回值 HRESULT是怎样编码的:
//  Values are 32 bit values layed out as follows:
//
//  3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
//  1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
//  +-+----+-------------------------+---------------------------------+
//  |S| Res|     Facility            |     Code                        |
//  +-+----+-------------------------+---------------------------------+
//
//  where
//
//      S - is the severity code
//
//          0 - Success         //0时,根据计算机的编码,为正数 
//          1 - Error
//
//      Res- is a reserved bit
//
//      Facility - is the facility code
//
//      Code - is the facility''s status code
所以,以下的宏可以用来判断调用是否成功:
#define SUCCEEDED(hr)(long(hr)>=0)
#define FAILED(hr)(long(hr)<0)

每个标准的COM组件都需要一个接口定义文件,文件的扩展名为IDL

IDL 例子:IUnknow接口的定义文件
[
  local,
  object,
  uuid(00000000-0000-0000-C000-000000000046),
  pointer_default(unique)
]

interface IUnknown
{
    typedef [unique] IUnknown *LPUNKNOWN;

cpp_quote("//")
cpp_quote("// IID_IUnknown and all other system IIDs are provided in UUID.LIB")
cpp_quote("// Link that library in with your proxies, clients and servers")
cpp_quote("//")

    HRESULT QueryInterface(
        [in] REFIID riid,
        [out, iid_is(riid)] void **ppvObject);
    ULONG AddRef();
    ULONG Release();
}

[local]属性禁止产生网络代码。
[object]属性是表明定义的是一个COM接口,而不是DEC风格的接口。
[uuid]属性给接口一个GUID。
[unique]属性表明null(空)指针为一个合法的参数值。
[pointer_defaul]属性所有的内嵌指针指定一个默认指针属性
typedef [unique] IUnknown *LPUNKNOWN;这是一个类型定义
cpp_quote这个比较有趣,这是一个在idl文件写注解的方法。这些注解将保存到***.h和***_i.c文件中
[in]表示这个参数是入参
[out]表示这个参数是出参
[iid_is(riid)]表示这个参数需要前一个的riid 参数。
其中 AddReft() 和Release()负责对象引用计数用的,而 QueryInterface()方法是用于查询所实现接口用的。每当COM组件被引用一次就应调用一次AddRef()方法。而当客户端在释放COM组件的某个接口时就需要调用Release()方法。
注意:所有具有out属性的参数都需要是指针类型。

COM要求(最基本的要求)所有的接口都需要从IUnknown接口直接或间接继承

一个比较简单的COM
此例子共有四个文件组成: 

           
           
文件名说明
Interface.h接口类定义文件
Math.h和Math.cpp实现类文件
Simple.cpp 主函数文件这里用来当作COM的客户端    

2.1 interface.h 文件

#ifndef INTERFACE_H
#define INTERFACE_H
#include <unknwn.h>

//{7C8027EA-A4ED-467c-B17E-1B51CE74AF57}
static const GUID IID_ISimpleMath = 
{ 0x7c8027ea, 0xa4ed, 0x467c, { 0xb1, 0x7e, 0x1b, 0x51, 0xce, 0x74, 0xaf, 0x57 } };

//{CA3B37EA-E44A-49b8-9729-6E9222CAE84F}
static const GUID IID_IAdvancedMath = 
{ 0xca3b37ea, 0xe44a, 0x49b8, { 0x97, 0x29, 0x6e, 0x92, 0x22, 0xca, 0xe8, 0x4f } };

interface ISimpleMath : public IUnknown
{
public:
	virtual int Add(int nOp1, int nOp2) = 0;		
	virtual int Subtract(int nOp1, int nOp2) = 0;
	virtual int Multiply(int nOp1, int nOp2) = 0;
	virtual int Divide(int nOp1, int nOp2) = 0;
};

interface IAdvancedMath : public IUnknown
{
public:
	virtual int Factorial(int nOp1) = 0;
	virtual int Fabonacci(int nOp1) = 0;
};
#endif    
此文件首先 #include <unknwn.h> 将 IUnknown 接口定义文件包括进来。
接下来定义了两个接口,GUID(Globally Unique Identifier全局唯一标识符)它能保证时间及空间上的唯一。
ISmipleMath接口里定义了四个方法,而IAdvancedMath接口里定义了二个方法。这些方法都是虚函数,而整个 ISmipleMath 与 IAdvancedMath 抽象类就作为二进制的接口。
2.2 math.h文件
#include "interface.h"

class CMath : public ISimpleMath,
			  public IAdvancedMath
{
private:
	ULONG m_cRef;

private:
	int calcFactorial(int nOp);
	int calcFabonacci(int nOp);

public:
	//IUnknown Method
	STDMETHOD(QueryInterface)(REFIID riid, void **ppv);
	STDMETHOD_(ULONG, AddRef)();
	STDMETHOD_(ULONG, Release)();

	//	ISimpleMath Method
	int Add(int nOp1, int nOp2);
	int Subtract(int nOp1, int nOp2);
	int Multiply(int nOp1, int nOp2);
	int Divide(int nOp1, int nOp2);

	//	IAdvancedMath Method
	int Factorial(int nOp);
	int Fabonacci(int nOp);
};    
此类为实现类,他实现了ISmipleMath和IAdvancedMath两个接口类(当然也可以只实现一个接口类)。
请注意:m_cRef 是用来对象计数用的。当 m_cRef 为0组件对象应该自动删除。
2.3 math.cpp文件
#include "interface.h"
#include "math.h"

STDMETHODIMP CMath::QueryInterface(REFIID riid, void **ppv)
{//	这里这是实现dynamic_cast的功能,但由于dynamic_cast与编译器相关。
	if(riid == IID_ISimpleMath)
		*ppv = static_cast
         
         
          
          (this);
	else if(riid == IID_IAdvancedMath)
		*ppv = static_cast
          
          
           
           (this);
	else if(riid == IID_IUnknown)
		*ppv = static_cast
           
           
            
            (this);
	else {
		*ppv = 0;
		return E_NOINTERFACE;
	}

	reinterpret_cast
            
            
             
             (*ppv)->AddRef();	//这里要这样是因为引用计数是针对组件的
	return S_OK;
}

STDMETHODIMP_(ULONG) CMath::AddRef()
{
	return ++m_cRef;
}

STDMETHODIMP_(ULONG) CMath::Release()
{
	ULONG res = --m_cRef;	// 使用临时变量把修改后的引用计数值缓存起来
	if(res == 0)		// 因为在对象已经销毁后再引用这个对象的数据将是非法的
		delete this;
	return res;
}

int CMath::Add(int nOp1, int nOp2)
{
	return nOp1+nOp2;
}

int CMath::Subtract(int nOp1, int nOp2)
{
	return nOp1 - nOp2;
}

int CMath::Multiply(int nOp1, int nOp2)
{
	return nOp1 * nOp2;
}

int CMath::Divide(int nOp1, int nOp2)
{
	return nOp1 / nOp2;
}

int CMath::calcFactorial(int nOp)
{
	if(nOp <= 1)
		return 1;

	return nOp * calcFactorial(nOp - 1);
}

int CMath::Factorial(int nOp)
{
	return calcFactorial(nOp);
}

int CMath::calcFabonacci(int nOp)
{
	if(nOp <= 1)
		return 1;

	return calcFabonacci(nOp - 1) + calcFabonacci(nOp - 2);
}

int CMath::Fabonacci(int nOp)
{
	return calcFabonacci(nOp);
}
 CMath::CMath()
{
	m_cRef=0;
}   
            
            
           
           
          
          
         
         
此文件是CMath类定义文件。

2.4 simple.cpp文件
#include "math.h"
#include <iostream>

using namespace std;

int main(int argc, char* argv[])
{
	ISimpleMath *pSimpleMath = NULL;//声明接口指针
	IAdvancedMath *pAdvMath = NULL;

	
         
         
          
          
           
           
            
            
             
             //创建对象实例,我们暂时这样创建对象实例,COM有创建对象实例的机制
	CMath *pMath = new CMath;	

	
             
             
              
               
                
                
                  //查询对象实现的接口ISimpleMath pMath->QueryInterface(IID_ISimpleMath, (void **)&pSimpleMath); if(pSimpleMath) cout << "10 + 4 = " << pSimpleMath->Add(10, 4) << endl; 
                  
                   
                    
                    
                      //查询对象实现的接口IAdvancedMath pSimpleMath->QueryInterface(IID_IAdvancedMath, (void **)&pAdvMath); if(pAdvMath) cout << "10 Fabonacci is " << pAdvMath->Fabonacci(10) << endl; pAdvMath->Release(); pSimpleMath->Release(); return 0; } 
                     
                    
                   
                  
                 
                
              
             
             
            
            
           
           
          
          
         
         
此文件相当于客户端的代码,首先创建一个CMath对象,再根据此对象去查询所需要的接口,如果正确得到所需接口指针,再调用接口的方法,最后再将接口的释放掉。

2.5 Math组件的二进制结构图



                              图1.3 Math组件二进制结构图













  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值