前面一篇文章讲述了怎么样通过GetIDsOfNames和Invoke来调用一个支持Idispach的COM组件。
看起来好像很麻烦,实际上,COM已经提供了一个专门的智能指针来解决这个问题。
CComDispatchDriver
看一下它的定义,实际上它就是一个特殊的CComQIPtr。
- typedef CComQIPtr<IDispatch, &__uuidof(IDispatch)> CComDispatchDriver;
typedef CComQIPtr<IDispatch, &__uuidof(IDispatch)> CComDispatchDriver;
如果COM组件不支持IDispatch的话,那么在创建CComDispatchDriver的时候一定会失败。
使用其实也很简单,直接看个例子好了。
使用例子
- // 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;
- }
// 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组件的方法的。只是简化了用户使用。