前面我们说过vb不仅支持一般的接口方法调用,还支持通过IDispatch接口进行自动化调用。通过#import,VC可以很好的支持一般的接口调用,但对IDispatch接口没有提供直接的支持。为了能方便的调用IDispatch接口,我们需要自己开发一个辅助类。我们先看一个例子:我们通过IDispatch接口调用IProvider接口中的属性和方法
- __interface IProvider: IDispatch
- {
- [id(1),propget] HRESULT Value([out,retval] BSTR* pbstrValue);
- [id(1),propput] HRESULT Value([in] BSTR bstrValue);
- [id(2)] HRESULT Echo([in] BSTR bstrMessage1, [out,retval] BSTR* pbstrMessage2);
- };
vb
- '获取属性值
- sValue=oDispatch.Value
- '设置属性值
- oDispatch.Value=sValue
- '调用方法
- sMessage2=oDispatch.Echo("hello world!")
vb般的vc++
- //获取属性值
- _bstr_t bstrValue=CVB::get(pDispatch,L"Value");
- //设置属性值
- CVB::put(pDispatch,L"Value",bstrValue);
- //调用方法
- _bstr_t bstrMessage2=CVB::Invoke1( pDispatch, L"Echo", L"hello world!");
下面是CVB类的源代码,你也可以从CSDN资源直接下载
http://download.csdn.net/source/566053
- /* CVB by Kevin
- Version 1.0 (2008-08-01)
- ----------------------------------------
- email: heart@pimshell.com
- homepage: http://www.pimshell.com
- License
- -------
- Feel free to use this class, as long as you don't claim that you wrote it
- and this copyright notice stays intact in the source files.
- If you use this class in commercial applications, please send a short message
- to heart@pimshell.com
- Version history
- ---------------
- - 1.0 initial release
- */
- #pragma once
- #include <dispex.h>
- ///
- __declspec(selectany) VARIANT vtEmpty={VT_EMPTY};
- __declspec(selectany) VARIANT vtNull={VT_NULL};
- ///
- #define DISPATCH_METHOD_EX 0x10
- ///
- #define __SAFECALL_BEGIN /
- try{/
- #define __SAFECALL_END /
- /
- }/
- catch(_com_error& e){/
- return e.Error();/
- }/
- catch(...){/
- return E_FAIL;/
- }/
- r