Difference between coinitialize () and afxoleinit ()

Source: Internet
Author: User

Coinitialize () and afxoleinit () both initialize the com library, but what are their differences?


Ole is a technology built on top of COM, with a higher level than COM. Afxoleinit () calls oleinitialize (). In addition to calling coinitializeex () to initialize the com library, oleinitialize () also performs some other operations, these operations are required for OLE applications. These Ole applications include:

(1) clipboard;

(2) drag and drop;

(3) Object Linking and Embedding (the current Ole is no longer just the concept of Object Linking and Embedding );

(4) In-Place activation;

Which corresponds to afxoleinit () is afxoleterm ().


Afxoleinit () and afxoleterm () also need to be paired. However, in your program, afxoleterm () can not appear, because, MFC has already helped you (if you are interested, you can take a closer look at cwinthread: m_lpfnoletermorfreelib, and cwinapp inherits from cwinthread ).

Note: When your function repeatedly calls afxoleinit (), it cannot be automatically called by MFC. You need to explicitly call afxoleterm to clear the com library.


Coinitialize and afxoleinit

If afxoleinit () is used to initialize COM in the console main program of MFC, wordapp is called in DLL. createdispatch ("word. application ", null) failed, but use coinitialize () to succeed

After breakpoint debugging is set in the afxoleinit () function, you can know that the value of afxcontextisdll is true, so it does not call oleinitialize, and thus does not call coinitialize.

Msdn (if afxoleinit is called from an mfc dll, the call will fail. The failure
Occurs because the function assumes that, if it is called from a DLL, the OLE system was previusly initialized by the calling application .) it seems that this function treats the current project as a DLL. ^ _ ^. I wonder if it is an MFC bug.

Bool afxapi afxoleinit ()

{

_ Afx_thread_state * pstate = afxgetthreadstate ();

Assert (! Pstate-> m_bneedterm); // calling it twice?


// Special Case DLL context to assume that the calling app initializes Ole.

// For DLLs where this is not the case, those DLLs will need to initialize

// OLE for themselves via oleinitialize. This is done since MFC cannot provide

// Automatic uninitialize for DLLs because it is not valid to shutdown Ole

// During a dll_process_detach.
If (afxcontextisdll)

{

Pstate-> m_bneedterm =-1; //-1 is a special flag

Return true;

}


// First, initialize Ole

Scode SC =: oleinitialize (null );

If (failed (SC ))

{

// Warn about non-null success Codes

# Ifdef _ debug

Trace (traceole, 0, _ T ("Warning: oleinitialize returned scode = % S. \ n "),

Afxgetfullscodestring (SC ));

# Endif

Goto initfailed;

}

// Termination required when oleinitialize does not fail

Pstate-> m_bneedterm = true;


// Hook idle time and exit time for required Ole cleanup

Cwinthread * pthread; pthread = afxgetthread ();

Assert (pthread );

Pthread-> m_lpfnoletermorfreelib = afxoletermorfreelib;


// Allocate and initialize default message Filter

If (pthread-> m_pmessagefilter = NULL)

{

Pthread-> m_pmessagefilter = new colemessagefilter;

Assert (afxolegetmessagefilter ()! = NULL );

Afxolegetmessagefilter ()-> Register ();

}

Return true;


Initfailed:

Afxoleterm ();

Return false;

}

Repost the question

I have been debugging an MFC application that callafxoleinit () to initialize COM. the call has returned true, but I am catching com exceptions when trying to instantiate and use any COM objects-the error says that com has not been initialized. after stepping
Into the afxoleinit method, I can see why this is happening-there is a macro named 'afxcontextisdll 'That is returning true, and this is causing afxoleinit to immediatly return without calling oleinitialize. according to the documentation located here (http://msdn2.microsoft.com/en-us/library/e91aseaz (vs.80 ). aspx ),
This is expected behavior "If afxoleinit is called from an mfc dll". However, my application is an EXE.


From there, I created a new Win32 console application with MFC header files as a Windows application project to see if it was a project setting. upon calling afxoleinit in initinstance, I see the same behavior. I then created an new Win32 console application
With MFC header files as a console application project. the call to afxwininit trips up on the same macro (afxcontexisdll) and never callafxinitthread. I have also added a call to afxoleinit to this project and I am seeing the same behavior-oleinitialize
Never gets called.


The strange thing is that there are other projects in the application that are executables, and call afxoleinit successfully (ie, stepping into this method, the macro afxcontextisdll is false, and oleinitialize gets called ). the only difference is that these
Projects were created with an earlier version of Visual Studio... this project was made with vs2k5. suspecting that it had to do with some project setting, I made a copy of one of these executables 'Project file, 'gutted' it by adding the new application's
Files and include libraries, but still am seeing


Differences between coinitializeex and coinitialize in COM

Coinitialize and coinitializeex are all windows APIs. They mainly tell windows how to create COM objects for programs. The reason is that the program calls com library functions (except cogetmalloc and memory allocation functions) you must initialize the com library before.
Coinitialize indicates that it is created in a single thread mode.

Coinitializeex can specify coinit_multithreaded to be created in multiple threads.

When creating a single-threaded COM server, you do not need to consider serialization.

Coinitialize does not load the com library. This function is only used to initialize the suite used by the current thread. When this function is used, the thread establishes a correspondence with a suite.

The suite mode of the thread determines how the thread calls the COM Object and whether the column set is required.

The suite is a very effective method in COM to solve the conflict of concurrent calls.

Before calling any COM functions, a thread needs to call coinitialize to load the com infrastructure (and to enter an apartment). Once a thread CILS coinitialize, the thread is free to call com APIs.

Provided provides the same functionality as coinitialize and also provides a parameter to explicitly specify the thread's concurrency model. The current implementation of coinitialize CILS parameters and specifies the concurrency model as single-Thread
Apartment. applications developed today shocould call coinitializeex rather than coinitialize.

Note: New applications should call coinitializeex instead of coinitialize. Otherwise, it is necessary to call coinitialize in each thread that calls com to initialize each thread's own suite.

Reference msdn. If you are interested, please refer to it.

A thread must call coinitializeex or coinitialize before calling any other COM library function doesn't the cogetmalloc function and other memory allocation CILS (cotaskmemalloc, cotaskmemfree,
Cotaskmemrealloc, And the imalloc methods on the task allocation supplied by cogetmalloc). Otherwise, the com library function will return co_e_notinitialized.


Once the concurrency model for a thread is set, it cannot be changed. A call to coinitializeex on a thread that was previusly initialized with a different concurrency model will fail and return rpc_e_changed_mode.


If neither concurrency model is specified by the dwcoinit parameter, the default is coinit_multithreaded.


Objects Created in a single-threaded apartment (STA) receive method callonly from their apartment's thread, so CILS are serialized and arrive only at message-queue boundaries (when the Win32 function peekmessage or sendmessage is called ).


Objects Created on a com thread in a Multithread apartment (MTA) must be able to receive method CILS from other threads at any time. you wocould typically implement some form of concurrency control in a multithreaded object's code using Win32 Synchronization
Primitives such as critical sections, semaphores, or mutexes to help protect the object's data.


When an object that is configured to run in the neutral threaded apartment (NTA) is called by a thread that is in either an sta or the MTA, that thread transfers to the NTA. if this thread subsequently CILS coinitializeex, the call fails and returns rpc_e_changed_mode.


Provided provides the same functionality as coinitialize and also provides a parameter to explicitly specify the thread's concurrency model. The current implementation of coinitialize CILS parameters and specifies the concurrency model as single-Thread
Apartment. applications developed today shocould call coinitializeex rather than coinitialize.


Because OLE technologies are not thread-safe, the oleinitialize function callcoinitializeex with the specified flag. As a result, an apartment that is initialized for Multithreaded object concurrency cannot use the features enabled by oleinitialize.


Because there is no way to control the order in which in-process servers are loaded or unloaded, do not call coinitialize, coinitializeex, or couninitialize from the dllmain function.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.