利用ATL创建com组件和如何在程序中使用组件的接口函数和设置接口的属性

这是一个ATL开发实例的流程:

1.       atl中插入一个atl实例,然后添加一个类,派生自ccmdtarget

2.       添加相应的属性或者方法,在这里需要明白一点的是,这个属性和方法其实是一个概念,只是添加一个属性就相当于添加了两个方法,一个用于获取属性的,一个用于设置属性的。

3.       注意一点:atl具有自注册的功能,我只需要对其进行build就可以实现注册的功能

4.       这就相当于创建了一个代码组件

接下来就是在工程中进行调用了:调用的步骤如下:

1.       首先我们用#import “…..dll”进行引入。注意这里引入的是dll而不是tlb(mfc写的组件调用的是tlb)

2.       afxoleinit()或者是Coinitialize(NULL)进行初始化。

3.       创建一个接口对象比如:IOperatorPtr m_p;

4.       对象实例化:eg:m_p.CreateInstance(__uuidof(Operator));即可

5.       用接口调用接口函数即可。

接下来是一个实例:

Atl中的主要代码:

STDMETHODIMP CFace::test(long Amount, BSTR *pbstrResult)

{

       // TODO: Add your implementation code here

 

       TCHAR szBuf[512];

       WCHAR *wszBuf=new WCHAR[512];

       BSTR bstrNew;

       if (m_balance+Amount<0)

       {

              wsprintf(szBuf,"不能借款");

              MultiByteToWideChar(CP_ACP,0,szBuf,-1,wszBuf,512);

              bstrNew=::SysAllocString(wszBuf);

              *pbstrResult=bstrNew;

       }

       else

       {

              wsprintf(szBuf,"借款成功");

              MultiByteToWideChar(CP_ACP,0,szBuf,-1,wszBuf,512);

              bstrNew=::SysAllocString(wszBuf);

              *pbstrResult=bstrNew;

       }

       return S_OK;

}

 

STDMETHODIMP CFace::get_Balance(long *pVal)

{

       // TODO: Add your implementation code here

       *pVal=m_balance;

       return S_OK;

}

 

STDMETHODIMP CFace::put_Balance(long newVal)

{

       // TODO: Add your implementation code here

       m_balance=newVal;

       return S_OK;

}

下面是在程序中对这个代码组件的调用的主要代码,初始化和实例化都已经在initialdialog中完成:

void CAaDlg::OnButton1()

{

       // TODO: Add your control notification handler code here

       UpdateData();

       BSTR str;

//     CoInitialize(NULL);

//  if (FAILED(m_p.CreateInstance(__uuidof(Face))))

//  {

//          AfxMessageBox("not found");

//    }

       str=m_p->test(m_data);

       CString s=(CString)str;

       AfxMessageBox(s);

}

 

void CAaDlg::OnButton2()

{

       // TODO: Add your control notification handler code here

       UpdateData();

//     IFacePtr ptr;

//     ptr.CreateInstance(__uuidof(Face));

//     ptr->put_Balance(m_money);

       m_p->put_Balance(m_money);

       MessageBox("存款成功");

}

 

void CAaDlg::OnButton3()

{

       // TODO: Add your control notification handler code here

//     CoInitialize(NULL);

       long l;

//    IFacePtr ptr;

//    if (FAILED(ptr.CreateInstance(__uuidof(Face))))

//    {

//           AfxMessageBox("not found");

//    }

//    ptr->get_Balance(&l);

       m_p->get_Balance(&l);

       CString str;

       str.Format("%d",l);

       MessageBox(str);

}

注意:在接口的设计的时候,方法的参数的第二个为输出参数,在程序中进行调用的时候,我们调用的接口方法的参数只有一个。如果写两个参数的话编译器是通不过的。可以再外面设置一个变量用来获取接口方法返回的值。

posted @ 2009-11-25 12:24  luck_net  阅读(728)  评论(2编辑  收藏  举报