COM开发与引用

在VC6.0中编写COM组件,使用VC6.0调用

(1)VC6.0编写COM组件

使用VC6.0建立COM组件,工程类型:ATL COM AppWizard

程序代码:

接口:

interface IAdd : IDispatch
        {
                [id(1), helpstring("method iadd")] HRESULT iadd([in]int a, [in]int b, [out]int * c);
                [id(2), helpstring("method fadd")] HRESULT fadd([in]float a, [in]float b, [out]float * c);
                [id(3), helpstring("method isub")] HRESULT isub([in]int a, [in]int b, [out]int * c);
        };
      


实现:

STDMETHODIMP CAdd::iadd(int a, int b, int *c)
{
        // TODO: Add your implementation code here
        *c = a + b;

        return S_OK;
}

STDMETHODIMP CAdd::fadd(float a, float b, float *c)
{
        // TODO: Add your implementation code here
        *c = a + b;

        return S_OK;
}

STDMETHODIMP CAdd::isub(int a, int b, int *c)
{
        // TODO: Add your implementation code here
        *c = a - b;

        return S_OK;
}
编写registry文件:先编译后,再修改为下面形式重新编译
HKCR
{
 testcom.Add.1 = s 'Add Class'
 {
  CLSID = s '{40D045E9-AF1E-4585-B8D8-6E4EB29B75EB}'
 }
 testcom.Add = s 'Add Class'
 {
  CLSID = s '{40D045E9-AF1E-4585-B8D8-6E4EB29B75EB}'
  CurVer = s 'AddCom.Add.1'
 }
 NoRemove CLSID
 {
  ForceRemove {40D045E9-AF1E-4585-B8D8-6E4EB29B75EB} = s 'Add Class'
  {
   ProgID = s 'testcom.Add.1'
   VersionIndependentProgID = s 'testcom.Add'
   ForceRemove 'Programmable'
   InprocServer32 = s '%MODULE%'
   {
    val ThreadingModel = s 'Apartment'
   }
   'TypeLib' = s '{C0322942-65A2-408D-831A-159C1F772158}'
  }
 }
}

 


(2)VC6.0编写调用程序

使用VC6.0建立MFC应用程序UseCOM,调用刚刚建立的COM组件

将上面程序AddCom生成的AddCom.dll放入本程序的工程目录和程序生成目录中

在StdAfx.h中加入:

#import "AddCom.dll" no_namespace

 

编译stdAfx.cpp文件,这样就可以引用AddCom.dll组件的接口,引用接口对象会显示它的方法与变量。顺序一定很重要,先放入UseCom.dll再编译,否则会出现不显示接口对象的方法与变量等情形。

程序代码:

void CUseComDlg::OnBUTTONUse() 
{
        // TODO: Add your control notification handler code here
        CString strResult;
        CoInitialize(NULL);//NULL换成0也可以
        IAddPtr m_add = NULL;
        HRESULT hr = S_OK;
        hr = m_add.CreateInstance(__uuidof(Add));

        int d_a = 90;
        int d_b = 10;
        int d_c;
        int d_d;
        float f_a = 1;
        float f_b = 2;
        float f_c;
 
        m_add->_IAdd(d_a,d_b,&d_c);
        m_add->fadd(f_a,f_b,&f_c);
        m_add->isub(d_a,d_b,&d_d);

        strResult.Format("返回结果:%d; %f; %d",d_c,f_c,d_d);
        MessageBox(strResult,"结果",MB_OK);

        m_add.Release();
        m_add = NULL;
        CoUninitialize();   
        
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值