Speak with code
ComTest implements two interfaces: ICmd, IStr, and ICmd. There is a function -- Add, and IStr has a function -- Cat, which is used to describe the usage of smart pointers, so it is not listed, the attachment contains the project code. The COM component does not provide the source code.
- # Include <atlbase. h>
- # Include <atlcom. h>
-
- # If 0
- # Import "ComTest. tlb" no_namespace // The third method uses this line to import the tlb Type Library without namespaces
- # Endif
-
- // Use either of the following two methods:
- # Include "ComTest_ I .c"
- # Include "ComTest. h"
-
- # Include <stdio. h>
- # Include <stdlib. h>
-
- Using namespace ATL;
-
- Int main ()
- {
- CoInitialize (NULL );
- # If 0
- // Method 3
- ICmdPtr cmd = NULL; // declare an ICmdPtr smart pointer and create an instance that is similar to the one used by ADO.
- Cmd. CreateInstance (_ uuidof (Cmd ));
- Int sum;
- Cmd-> Add (1, 2, & sum );
- Printf ("% d \ n", sum );
- Cmd. Release (); // fo Yue: Indispensable
-
- // Method 1
- CComPtr <IUnknown> pUnk; // defines a smart pointer
- CComQIPtr <ICmd> pCmd;
- HRESULT hr;
-
- Hr = pUnk. CoCreateInstance (CLSID_Cmd, NULL, CLSCTX_INPROC); // create an IUnknown instance on the pointer's COM. It's just a bit difficult to understand.
- Hr = pUnk. QueryInterface (& pCmd); // equivalent to the object for creating ICmd
- Int sum;
- Hr = pCmd-> Add (1, 2, & sum );
- Printf ("% d \ n", sum );
- // Remember to Release
- PUnk. Release ();
- PCmd. Release ();
- # Endif
- // Method 2
- CComPtr <IUnknown> pUnk;
- PUnk. CoCreateInstance (CLSID_Cmd, NULL, CLSCTX_INPROC); // same as the first method
- CComQIPtr <ICmd> pCmd = pUnk; // create an ICmd object
- CComQIPtr <IStr> pStr = pUnk; // create an IStr object
- Int sum;
-
- PCmd-> Add (1, 2, & sum );
- Printf ("% d \ n", sum );
- CComBSTR bstr;
- PStr-> Cat (BSTR) "d", (BSTR) "e", & bstr );
- Printf ("% S \ n", bstr );
- // Release is indispensable.
- PStr. Release ();
- PCmd. Release ();
- PUnk. Release ();
-
- CoUninitialize ();
- System ("pause ");
- Return EXIT_SUCCESS;
- }
This article is from the "Studoc" blog, please be sure to keep this source http://studoc.blog.51cto.com/1284909/282721