如何编写、调用一个简单的com示例?

1 编写个简单的com组件
1.1 我们试着用ATL开发个com应用,打开vc6,选择File -> New -> Project -> ATL COM AppWizard -> Project Name 处输入AtlSimple -> OK -> Finish !
1.2 Insert -> New ATL Object -> Simple Object -> Next -> Short Name 处输入Math -> OK!
1.3 在接口IMath的右键菜单中,选择Add Method,在Method Name处输入Add,Parmeters处输入 int a,int b,int* c,后确定。
1.4 实现Add方法:
 STDMETHODIMP CMath::Add(int a, int b, int* c)
 {
  *c = a + b;
  return S_OK;
 }

2 用c++对话框程序调用com组件,实现其客户端
2.1 在调用com处,包含头文件,其中包含接口本身定义、接口IID定义、COM对象CLSID定义
 #include "..\AtlSimple\AtlSimple.h"
 #include "..\AtlSimple\AtlSimple_i.c"
 //根据你实际情况调整头文件路径
2.2 调用示例:
 void CAtlClientDlg::OnButton2()
 {
  ::CoInitialize(NULL);
  HRESULT hr;
  IMath* pIntf = NULL;
  hr = CoCreateInstance(CLSID_Math, NULL, CLSCTX_SERVER , IID_IMath, (void **)& pIntf);
  if(SUCCEEDED(hr))
  {
   int c = 0;
   pIntf->Add(1,2,&c);
   CString str;
   str.Format("1+2=%d",c);
   AfxMessageBox(str,0,0);
   pIntf->Release();
  }
  ::CoUninitialize();
 }
2.3 编译连接测试正确性

posted @ 2007-05-31 17:23  虚幻  阅读(377)  评论(0编辑  收藏  举报