COM调用2
2012-07-12 12:52 江上渔者 阅读(349) 评论(0) 编辑 收藏 举报// 原型:
STDMETHOD(Method1)(LONG la, BSTR bstra, LONG* pla, BSTR* pbstra, LONG* plResult);
xxxCOMInterface.h
#pragma once #include <atlbase.h> #include <atlcom.h> #define R_SUCCESS 0 #define R_ERROR -1 class xxxCOMInterface { private: IDispatch* m_pxxxCOMDispatch; public: xxxCOMInterface(void); ~xxxCOMInterface(void); long CreateInstance(); long Method1(long la_In,BSTR bstra_In,long* pla_Out,BSTR* pbstra_Out); };
xxxCOMInterface.cpp
#include "xxxCOMInterface.h" xxxCOMInterface::xxxCOMInterface(void) { CoInitialize(NULL); m_pxxxCOMDispatch = NULL; } xxxCOMInterface::~xxxCOMInterface(void) { m_pxxxCOMDispatch = NULL; CoUninitialize(); } long xxxCOMInterface::CreateInstance() { long lResult = R_SUCCESS; HRESULT hr; CLSID clsid; hr = CLSIDFromProgID(L"atlpro.xxx",&clsid); if (FAILED(hr)) { lResult = R_ERROR; } else { hr = CoCreateInstance( clsid, NULL, CLSCTX_INPROC_SERVER, IID_IDispatch, (void**)&m_pxxxCOMDispatch); if (FAILED(hr)) { lResult = R_ERROR; } } return lResult; } long xxxCOMInterface::Method1(long la_In,BSTR bstra_In,long* pla_Out,BSTR* pbstra_Out) { long lResult = R_SUCCESS; HRESULT hr; DISPID dispid; LPOLESTR func = L"Method1"; hr = m_pxxxCOMDispatch->GetIDsOfNames( IID_NULL, &func, 1, GetUserDefaultLCID(), &dispid); if (FAILED(hr)) { lResult = R_ERROR; } else { VARIANT vResult; DISPPARAMS dispparams; memset(&dispparams,0,sizeof dispparams); dispparams.cArgs = 4; dispparams.cNamedArgs = 0; dispparams.rgvarg = new VARIANT[dispparams.cArgs]; dispparams.rgvarg[3].vt = VT_I4; dispparams.rgvarg[3].lVal = la_In; dispparams.rgvarg[2].vt = VT_BSTR; dispparams.rgvarg[2].bstrVal = bstra_In; dispparams.rgvarg[1].vt = VT_BYREF|VT_I4; dispparams.rgvarg[1].plVal = pla_Out; dispparams.rgvarg[0].vt = VT_BYREF|VT_BSTR; dispparams.rgvarg[0].pbstrVal = pbstra_Out; hr = m_pxxxCOMDispatch->Invoke( dispid, IID_NULL, GetUserDefaultLCID(), DISPATCH_METHOD, &dispparams, &vResult, NULL, NULL); if (FAILED(hr)) { lResult = R_ERROR; } else { lResult = vResult.lVal; } } return lResult; }
// COMTest.cpp
// comtest.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "xxxCOMInterface.h" #include <iostream> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { long lResult = R_SUCCESS; xxxCOMInterface xxx; lResult = xxx.CreateInstance(); if (lResult != R_SUCCESS) { cout<<"创建COM实例失败!"<<endl; } else { long la_In = 10; BSTR bstra_In = SysAllocString(L"test"); long la_Out = 0; BSTR bstra_Out = NULL; lResult = xxx.Method1( la_In, bstra_In, &la_Out, &bstra_Out); if (lResult != R_SUCCESS) { cout<<"调用Method1方法失败!"<<endl; } cout<<"调用Method1方法成功!"<<endl; cout<<la_In<<"\t"<<bstra_In<<"\t"<<la_Out<<"\t"<<bstra_Out<<endl; SysFreeString(bstra_In); SysFreeString(bstra_Out); } cin>>lResult; return 0; }