IDispatch接口 - Part II -CComDispatchDriver智能指针

前面一篇文章讲述了怎么样通过GetIDsOfNames和Invoke来调用一个支持Idispach的COM组件。

看起来好像很麻烦,实际上,COM已经提供了一个专门的智能指针来解决这个问题。

CComDispatchDriver

看一下它的定义,实际上它就是一个特殊的CComQIPtr。

  1. typedef CComQIPtr<IDispatch, &__uuidof(IDispatch)> CComDispatchDriver; 
typedef CComQIPtr<IDispatch, &__uuidof(IDispatch)> CComDispatchDriver;
如果COM组件不支持IDispatch的话,那么在创建CComDispatchDriver的时候一定会失败。

使用其实也很简单,直接看个例子好了。

使用例子

  1. // ConsoleApplication4.cpp : Defines the entry point for the console application. 
  2. // 
  3.  
  4. #include "stdafx.h" 
  5.  
  6. #include <thread> 
  7. #include <atlbase.h> 
  8. #include <atlcom.h> 
  9. #include <algorithm> 
  10. #include <vector> 
  11. #include <memory> 
  12.  
  13. #include "../MyCom/MyCom_i.h" 
  14. #include "../MyCom/MyCom_i.c" 
  15.  
  16. int _tmain(int argc, _TCHAR* argv[]) 
  17.     CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); 
  18.      
  19.     CComDispatchDriver dsp; 
  20.     dsp.CoCreateInstance(CLSID_MyCar); 
  21.  
  22.     CComVariant rt; 
  23.     dsp.GetPropertyByName(L"Gas", &rt); 
  24.     LONG total = rt.lVal; 
  25.  
  26.     CComVariant p1; 
  27.     p1.vt = VT_I4; 
  28.     p1.lVal = 12; 
  29.  
  30.     CComVariant p2; 
  31.     p2.vt = VT_I4 | VT_BYREF; 
  32.     LONG Gas = 0; 
  33.     p2.byref = &Gas; 
  34.  
  35.     dsp.Invoke2(L"AddGas", &p1, &p2, NULL); 
  36.  
  37.     CComVariant totalGas; 
  38.     dsp.GetPropertyByName(L"Gas", &totalGas); 
  39.     total = totalGas.lVal; 
  40.  
  41.     dsp.Release(); 
  42.  
  43.     CoUninitialize(); 
  44.      
  45.     return 0; 
// ConsoleApplication4.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include <thread>
#include <atlbase.h>
#include <atlcom.h>
#include <algorithm>
#include <vector>
#include <memory>

#include "../MyCom/MyCom_i.h"
#include "../MyCom/MyCom_i.c"

int _tmain(int argc, _TCHAR* argv[])
{
    CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
    
    CComDispatchDriver dsp;
    dsp.CoCreateInstance(CLSID_MyCar);

    CComVariant rt;
    dsp.GetPropertyByName(L"Gas", &rt);
    LONG total = rt.lVal;

    CComVariant p1;
    p1.vt = VT_I4;
    p1.lVal = 12;

    CComVariant p2;
    p2.vt = VT_I4 | VT_BYREF;
    LONG Gas = 0;
    p2.byref = &Gas;

    dsp.Invoke2(L"AddGas", &p1, &p2, NULL);

    CComVariant totalGas;
    dsp.GetPropertyByName(L"Gas", &totalGas);
    total = totalGas.lVal;

    dsp.Release();

    CoUninitialize();
    
	return 0;
}
这个代码很简单,看一下就知道怎么通过CComDispatchDriver来调用支持IDispatch接口的COM组件了。其实CComDispatchDriver内部还是通过GetIDsOfNames和Invoke等函数来调用COM组件的方法的。只是简化了用户使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值