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

来源:互联网 发布:照片审核工具 mac 编辑:程序博客网 时间:2024/06/06 08:40

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

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

CComDispatchDriver

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

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

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

使用例子

[cpp] view plaincopyprint?
  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; 
这个代码很简单,看一下就知道怎么通过CComDispatchDriver来调用支持IDispatch接口的COM组件了。其实CComDispatchDriver内部还是通过GetIDsOfNames和Invoke等函数来调用COM组件的方法的。只是简化了用户使用。

0 0