在MFC程序中调用COM

14 篇文章 1 订阅

Intializing

In order to to use COM in your MFC app, you will need to call AfxOleInit() in the InitInstance() of your application class.

Creating the Wrapper class

Open the Classwizard from the View menu. Click [Add Class]. Select 'From a type library...'.

Select the Type Library. This is usually a file with a '.tlb' extension supplied with the dll/exe/ocx, or it may be contained within the dll/exe/ocx file.

In the 'Confirm Classes' dialog box, select an interface, then edit the names of the files which will be auto-generated. I suggest you put '_Wrapper' at the end of both the class name and the file names.For instance: 'IExample_Wrapper', 'Example_Wrapper.h', 'Example_Wrapper.c'.

The new class will be added to the project and should show up in the ClassView tab of the Workspace. This class will be derived from COleDispatchDriver.

Instantiating the COM object

You must create an instance of the COM object by using the CreateDispatch() member of the wrapper class, passing it either a GUID or the text identifier. Note that you must refer to the 'package' name, the Interface, and the version number of the Interface.

e.g.

CExample_Wrapper exampleWrapper;
exampleWrapper.CreateDispatch(_T("Example.Example.1"));

Using the COM object's methods

The auto-generated wrapper will have methods for each of the COM methods.These methods do not return the HRESULT. Instead they will return the [out, return] parameter if any.

If a COM methods returns anything other than S_OK, a COleDispatchException will be thrown. You may detect this with a try/catch block.

e.g.

try
{
    int iTemp = exampleWrapper.GetValue();ࠠ
}
catch(COleDispatchException* pEx)
{
    //do something.
}
CoInitialize()和AfxOleInit()的用法
OLE是建立在COM之上的技术,层次比COM要高。

AfxOleInit():

AfxOleInit()调用的是OleInitialize(),而OleInitialize()除了调用CoInitializeEx()来初始化COM库外,还进行一些其它的操作,这些操作对OLE应用来说是必须的,这些OLE应用包括:  
  (1)Clipboard;  
  (2)Drag&drop;  
  (3)Object linking and embedding(现在的OLE,已不再仅仅是Object linking and embedding的概念);  
  (4)In-place   activation;

  与AfxOleInit()对应的是,AfxOleTerm()。但是,在你的程序中,AfxOleTerm()可以不出现,这是因为,MFC已经帮你做好了(有兴趣的话,你可以仔细研究一下CWinThread::m_lpfnOleTermOrFreeLib,而CWinApp是从 CWinThread继承的)。


CoInitialize():

CoInitialize和CoUninitialize必须成对使用, CoInitialize()放在C**App::InitInstance(..), CoUninitialize房子C**App::ExitInstance()内。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值