Reference http://www.vckbase.com/document/viewdoc? Id = Code 1500
Summarized several methods of COM Initialization
1. Get the ifun interface pointer through iunknown
Coinitialize (null); <br/> iunknown * punk = NULL; <br/> ifun * pfun = NULL; <br/> hR =: cocreateinstance (clsid_fun, null, clsctx_inproc_server, iid_iunknown, (lpvoid *) & punk); <br/> punk-> QueryInterface (iid_ifun, (lpvoid *) & pfun ); <br/> ....... // call the pfun method implementation code <br/> couninitialize ();
2. Get the ifun interface pointer without passing through iunknown
Coinitialize (null); <br/> ifun * pfun = NULL; <br/> hR =: cocreateinstance (clsid_fun, null, clsctx_inproc_server, iid_iunknown, (lpvoid *) & pfun); <br/> ....... // call the pfun method implementation code <br/> couninitialize ();
3. Use ccomptr smart pointer Initialization
// Call the afxoleinit () function during COM Initialization <br/> ccomptr <iunknown> spunk; <br/> ccomptr <ifun> spfun; // define the ifun smart pointer <br/> hresult hr; <br/> hR = spunk. cocreateinstance (clsid_fun); <br/> If (failed (HR) Throw (_ T ("no registered component? "); <Br/> hR = spunk. QueryInterface (& spfun); <br/> If (failed (HR) Throw (_ T (" actually no interface? "));
4. No longer passed iunknown smart pointer Initialization
// COM Initialization is called using the afxoleinit () function. <br/> ccomqiptr <ifun, & iid_ifun> spfun; // defines the ifun smart pointer <br/> hresult hr; <br/> hR = spfun. cocreateinstance (clsid_fun); <br/> spfun-> method ().... // call the ifun function as a pointer
5. afxoleinit Initialization is not required, but smart pointers must be released.
<Br/> coinitialize (null); <br/> ccomqiptr <ifun, & iid_ifun> spfun; <br/> spfun. cocreateinstance (clsid_fun); <br/> ..... <br/> spfun-> method (); <br/> spfun. release (); <br/> couninitialize ();
6. because in stdafx. in H # import, no_namespace is not used. Therefore, the namespace must be called comnamelib. This name is specified by the component IDL file library and needs to be called by afxoleinit () or coinitialize for initialization, however, the smart pointer must be released in couninitialize.
// In the STD file <br/> // # import ".. /testatl_3/debug/testatl_3.dll "<br/> // coinitialize (null); <br/> testatl_3lib: ifunptr spfun (_ uuidof (testatl_3lib: Fun )); <br/>... <br/> spfun-> method (); <br/>... <br/> // spfun. release (); <br/> // couninitialize ();