1.创建Calculate组件,添加IFun接口(注意:本例我们在Attributes中我们选择Apartment,Custom,Yes).在IFun接口中添加函数Add实现两数相加的功能(参数为[in] long n1, [in] long n2, [out, retval] long *pVal).代码如下:
STDMETHODIMP CCalCulate::Add(long n1, long n2, long *pVal)
{
// TODO: Add your implementation code here
*pVal = n1 + n2;
return S_OK;
}
2.添加IFun2接口,继承IFun接口.步骤如下:
(1)修改.idl文件:
在 interface IFun : IUnknown
{
[helpstring("method Add")] HRESULT Add([in] long n1, [in] long n2, [out, retval] long *pVal);
};
下添加代码:
[
object,
uuid(B9D75722-1950-405b-8BB6 -9788A6DB1DB2), //是接口IFun2的标志数,可由VS的GUIDGEN.exe产生
helpstring("IFun2 Interface"),
pointer_default(unique)
]
interface IFun2 : IFun
{
};
同时将末尾 coclass CalCulate函数改为
coclass CalCulate
{
interface IFun;
[default] interface IFun2;
};
(2) 修改CalCulate.h文件
将class ATL_NO_VTABLE CCalCulate :
public CComObjectRootEx<CComSingleThreadModel>,
public CComCoClass<CCalCulate, &CLSID_CalCulate>,
public IFun
改为class ATL_NO_VTABLE CCalCulate :
public CComObjectRootEx<CComSingleThreadModel>,
public CComCoClass<CCalCulate, &CLSID_CalCulate>,
public IFun2
在BEGIN_COM_MAP(CCalCulate)
COM_INTERFACE_ENTRY(IFun)
END_COM_MAP()
中添加COM_INTERFACE_ENTRY(IFun2)
(3) 在IFun2接口中添加Sub函数,方法同添加Add函数不再重复,只是实现时改为
*pVal = n1 - n2 返回两数差.
(4) 编写客户端代码,调用IFun2接口的Add和Sub函数.