在MFC程序中调用COM

来源:互联网 发布:启辰网络 编辑:程序博客网 时间:2024/06/13 22:31

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()内。
原创粉丝点击