COM调用
2012-03-15 12:04 江上渔者 阅读(292) 评论(0) 编辑 收藏 举报一、BCB
(1)导入模式
1、Component-》Import Component...-》Import a Type Library-》...
2、#include "xxx_TLB.h"
3、调用
CoInitialize(NULL);
IxxxDisp xxx;
xxx.BindDefault();
xxx.Method1();
CoUninitialize();
(2)自动化模式
CoInitialize(NULL);
Variant xxx = Variant::CreateObject("xxx.xxx");
Ret = xxx.OleFunction("Method1",...);
CoUninitialize();
注:BSTR*传出参数可以使用WideString类型,例如:Ret = xxx.OleFunction("Method1",&wsErrorMsg)。
(3)标准模式
1、创建对象
long CreateInstance( BSTR* pbstrErrorMsg_Out) // 返回的错误信息 { long lResult = R_SUCCESS; HRESULT hr; CLSID clsid; hr = CLSIDFromProgID(L"xxx.xxx", &clsid); if (FAILED(hr)) { lResult = R_ERROR; *pbstrErrorMsg_Out = SysAllocString(L"xxx.xxx"); } else { hr = CoCreateInstance( clsid, NULL, CLSCTX_INPROC_SERVER, IID_IDispatch, (void**)&xxx); if (FAILED(hr)) { lResult = R_ERROR; *pbstrErrorMsg_Out = SysAllocString(L"xxx.xxx"); } } return lResult; }
2、调用接口
// 初始化系统 long InitSystem( BSTR bstrUserName_In, // 用户名 BSTR bstrPassword_In, // 密码 BSTR* pbstrErrorMsg_Out) // 返回的错误信息 { long lResult = R_SUCCESS; DISPPARAMS dispparams; try { HRESULT hr; DISPID dispid; LPOLESTR func = L"InitSystem"; hr = xxx->GetIDsOfNames( IID_NULL, &func, 1, GetUserDefaultLCID(), &dispid); if (FAILED(hr)) { lResult = R_ERROR; } else { VARIANT vResult; memset(&dispparams,0,sizeof dispparams); dispparams.cArgs = 3; dispparams.cNamedArgs = 0; dispparams.rgvarg = new VARIANT[dispparams.cArgs]; dispparams.rgvarg[2].vt = VT_BSTR; dispparams.rgvarg[2].bstrVal = bstrUserName_In; dispparams.rgvarg[1].vt = VT_BSTR; dispparams.rgvarg[1].bstrVal = bstrPassword_In; dispparams.rgvarg[0].vt = VT_BYREF|VT_BSTR; dispparams.rgvarg[0].pbstrVal = pbstrErrorMsg_Out; hr = xxx->Invoke( dispid, IID_NULL, GetUserDefaultLCID(), DISPATCH_METHOD, &dispparams, &vResult, NULL, NULL); if (FAILED(hr)) { lResult = R_ERROR; } else { lResult = vResult.lVal; if (lResult == R_SUCCESS) m_lSystemCount++; } } } catch(...) { DELETEARRAY(dispparams.rgvarg) throw; } DELETEARRAY(dispparams.rgvarg) return lResult; }
3、释放对象
void ReleaseInstance() { if (xxx) { xxx->Release(); xxx = NULL; } }
二、MFC
1、Add-》Class...-》MFC-》MFC Class From TypeLib->...
2、#include "Cxxx.h"
3、调用
CoInitialize(NULL);
Cxxx xxx;
xxx.CreateDispatch("atl.xxx.1"); // ProgID
xxx.Method1();
xxx.ReleaseDispatch();
CoUninitialize();
三、C#
1、Add Reference...-》COM-》...
2、using ...
3、调用
Ixxx x = new xxxClass();
x.Method1();