给你一段VC调用IDispatch的原理性代码(摘自我的讲义,无版权)
IDispatch 调用 DispDll.Fun 组件中的Add加法函数
::CoInitialize(NULL);
HRESULT hr;
IDispatch *pDispatch=NULL;
try
{
CLSID clsid;
hr=::CLSIDFromProgID(L"DispDll.Fun",&clsid);
if(FAILED(hr)) throw(0);
hr=::CoCreateInstance(clsid,NULL,CLSCTX_SERVER,
IID_IDispatch,(LPVOID *)&pDispatch);
if(FAILED(hr)) throw(0);
OLECHAR *arrFunName[]={L"Add"};
DISPID dispID;
hr=pDispatch->GetIDsOfNames(IID_NULL,arrFunName,1,LOCALE_SYSTEM_DEFAULT,&dispID);
if(FAILED(hr)) throw(0);
VARIANT v[2];
v[0].vt=VT_I4; v[0].lVal=3; //加数(参数2)
v[1].vt=VT_I4; v[1].lVal=2; //被加数(参数1)
DISPPARAMS params={v,NULL,2,0};
/* params.rgvarg=v;
params.rgdispidNamedArgs=NULL;
params.cArgs=2;
params.cNamedArgs=0;
*/
VARIANT vResult;
hr=pDispatch->Invoke(dispID,IID_NULL,LOCALE_SYSTEM_DEFAULT,DISPATCH_METHOD,
¶ms,&vResult,NULL,NULL);
if(FAILED(hr)) throw(0);
CString s; s.Format("%d",vResult.lVal);
AfxMessageBox(s);
pDispatch->Release();
}
catch(...)
{
if(pDispatch) pDispatch->Release();
}
::CoUninitialize();
阅读(2769) | 评论(0) | 转发(0) |