如何编写、调用一个简单的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 编译连接测试正确性

转载于:https://www.cnblogs.com/unreal/articles/766706.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值