Design and application of "reprint" COM component (v)--write the first component in ATL

Source: Internet
Author: User

Original: http://vckbase.com/index.php/wv/1215.html

First, preface

1, if you are using vc5.0 and the previous version, please upgrade to vc6.0 or Vc.net 2003;

2. If you are using vc6.0 (ATL 3.0), please read this content;

3, if you are using Vc.net (ATL 7.0) Please read the next content; (of course, read the content of this article is also good)

4, this first component, in addition to all the COM components must be IUnknown interface, we implement a self-defined interface Ifun, it has two functions: Add () to complete the addition of two numbers, Cat () Complete the connection of two strings.

5. Below ... Listen carefully! Started:-).

Second, building an ATL project

Step 2.1: Create a Workspace (WorkSpace).

Step 2.2: In the workspace, create an ATL project (project). The sample program is called Simple1, and the DLL mode is selected, as shown in Figure I.

Figure I. Building an ATL DLL project

The Dynamic Link Library (DLL) represents a component program that builds a DLL.

executable (EXE) is a component program that establishes an EXE.

A service (EXE) represents a program that is built and executed after the system is started.

Allow merging of Proxy/stub code selects this option to merge the "proxy/stub" codes into the component program, otherwise it needs to be compiled separately to register the proxy stub program separately. Agent/stub, what is this concept? Do you remember what we introduced in the last book? When the caller invokes out-of-process or remote component functionality, the proxy/stub is actually responsible for data exchange. About the agent/stub of the specific turn and operation, and then again ...

Support MFC unless there are special reasons why we write an ATL program, it is best not to select the item. You might say, if there is no MFC support, what about the CString? Tell you a secret, the average person I do not tell him, I in the second half of my life by this secret alive:

1, you will STL it? Can be replaced with a string in STL;

2, I write a MyString class, hehe;

3, quietly, secretly, do not tell others (especially do not tell Microsoft), the MFC in the CString source to take over;

4, use CComBSTR class, at least can simplify our string operation;

5, directly with the API operation string, anyway, we all learn C language, are from here to do. (equal to not say, hehe)

Support MTS supports transactional processing, that is, COM + functionality is supported. COM + may introduce you in the 99th.

Iii. Adding an ATL object class

Step 3.1: Menu Insert\new ATL Object ... (or use the right mouse button to pop up the menu in the ClassView card) and select the object category to select the Simple object item. See Figure Ii.

Figure two, choose to build a simple COM object

Category Object Common component. There are many types of component objects that can be selected, but essentially, the wizard helps us to add some interfaces by default. For example, if we choose "Simple Object", then the wizard will add the IUnknown interface to our component, and if we select "Internet Explorer Object", the wizard will add a Iobjectwi to IE with the addition of the IUnknown interface. Thsite interface. Of course, we can simply add any interface manually.

Category Controls ActiveX controls. There are also many types of ActiveX that can be selected. We'll discuss this later in the introduction of ActiveX programming.

Category Miscellaneous auxiliary Miscellaneous components.

Categroy Data Access Database class component (I hate database programming, so I don't).

Step 3.2: Increase the custom class Cfun (interface Ifun) as shown in Figure three.

Figure III, the names of the entries in the class

In fact, we only need to enter the short name, other items will be filled in automatically. There's nothing to say, just take a look at the ProgID entry, the default ProgID is constructed as "project name. Short name".

Step 3.3: Fill in the interface properties, see Figure Four.

Figure IV, Interface properties

The threading model selects the threading models supported by the component. The thread in COM, I think is the most annoying, the most complicated part. The concept of COM threads and Apartments is reserved for follow-up introductions. Now ... Everybody choose Apartment, what does it mean? Simply put: These calls are queued when component functions are called in the thread. Therefore, in this mode, we can temporarily not consider the problem of synchronization. (Note 1)

Interface interface base type. Dual supports dual interfaces (note 2), which is very, very important, very common, but we don't speak today. Custom represents a customized excuse. Remember! Remember! Our first COM program in this, be sure to select it!!!! (If you've chosen the wrong one, please delete the entire content and try again.) )

Aggregation The components we write will be allowed to be aggregated by others (note 3) in the future. Only indicates that it must be aggregated to be used, somewhat like a pure virtual class in C + +, and you choose it if you are the chief engineer who is only responsible for designing but not writing the code yourself.

Whether the support ISupportErrorInfo supports rich information error handling interfaces. Talk about it later.

Support Connection Points Whether the connection point interface (event, callback) is supported. Talk about it later.

Free threaded Marshaler later also do not speak, even if killed you, I do not say! (Note 4)

Iv. Adding interface functions

Figure v. Bring up a menu that adds an interface method

Figure VI, add the interface function add

Figure VII, adding the interface function Cat

Please add the Add () function exactly as shown in Figure six, as the parameters of the cat () function in Figure VII are longer, I do not have the proper input space, please pay attention when you input. [In] indicates that the parameter direction is input; [out] indicates that the parameter direction is output; [Out,retval] indicates that the parameter direction is output and can be used as the return value of the result of the function operation. In a function, there can be multiple [in] and [out], but [retval] can have only one and be combined with [out] at the last position. (Note 5)

Figure VIII, the diagram after the completion of the interface function definition

As we all know, to change the class function in C + +, we need to modify two places: one is the function declaration of the class in the header file (. h), and the second is the implementation of the function body (. cpp) file. While we are now using ATL to write component programs, we also need to modify one place, which is the interface definition (IDL) file. Don't worry. IDL will be discussed next time.

As a result of the vc6.0 bug, you may not be able to show the style (figure eight) after adding the interface and interface functions. Workaround:

1 Close the project and reopen it This method is often effective
2 Close the IDE and run it again  
3 Open the IDL file, check that the interface function is correct, if it is not correct, modify the  
4 Open IDL file, modify it casually
(Add a space, and then delete the space), and then save
This method is often effective
5 Open the H/cpp file to check if the function exists or is correct, rectify any mistakes No Toand, do not finish this idiom psychological awkward
6 Remove the interface function from the Idl/h/cpp, and then I'll do it again.
7 Re-establish the project, reinstall the VC, reinstall Windows, smash the computer Hit!

V. Implement interface functions

Mouse double dot figure eight Cfun\ifun\add (...) You can begin the input function implementation:

STDMETHODIMP Cfun::add (Long N1, long N2, long *pval) {*pval = n1 + N2;return S_OK;}

  

This is too simple to waste "tongue". Below we implement the cat () function of the string connection:

STDMETHODIMP Cfun::cat (BSTR S1, BSTR S2, BSTR *pval) {int nLen1 =:: Sysstringlen (S1);//s1 character length int nLen2 =:: Sysstringle  n (S2);//s2 character Length *pval =:: SysAllocStringLen (S1, nLen1 + nLen2);//Construct a new BSTR and save the S1 first if (nLen2) {:: memcpy (*pval + NLEN1, S2, nLen2 * sizeof (WCHAR));//Then connect S2 to//wcscat (*pval, S2);} return S_OK;}

  

Student: The above function implementation is done entirely by invoking the basic API method.

Teacher: Yes, to tell the truth, it is quite cumbersome indeed.

Student: We are using memcpy () to complete the second string function, so why not use the function wcscat ()?

Teacher: In most cases, but you need to know: Because a BSTR contains a string length, the actual BSTR string content can be stored in the "L", and the function Wcscat () is the "L" as the end of the copy flag, so the data may be lost. Do you understand?

Student: Understand, understand. I've seen the data types of COM component design and application (c). So, teacher, is there a simple way to do that?

Teacher: Yes, you see ...

STDMETHODIMP Cfun::cat (BSTR S1, BSTR S2, BSTR *pval) {CComBSTR sresult (S1); Sresult.appendbstr (s2); *pval = Sresult.copy ( );//*pval = Sresult.detach (); return S_OK;}

  

Student: Haha, good! With CComBSTR, this is a lot easier. What is the difference between ccombstr::copy () and CComBSTR::D Etach ()?

Teacher: Ccombstr::copy () Creates a copy of a BSTR, and Ccombstr::copyto () has a similar function. and CComBSTR::D Etach () is to peel the object with the internal BSTR pointer, which is a little bit faster because there is no copy process. Be aware, however, that once stripped, you can no longer use the object.
Student: Teacher, you speak too cow, I admire you like the towering Taishan, straight into the sky ...

Teacher: stop,stop! Leave homework ...

1. Write this component first according to the content of today's speech;

2, whether you understand or do not understand, must go to observe IDL files, CPP files;

3, after compiling, see what kind of files are produced? If it is a text file, open it to look;

4. Download the sample program (vc6.0 version) of this article to compile and run to see the effect. Then preview the calling method in the sample program;

Student: I know, I want to go to the bathroom, I have to pee.

Teacher: Class dismissed! Don't forget to top my post ...

Vi. Summary

This article describes the steps to establish the first ATL component program, and how to use it, so stay tuned for COM component design and application (vii).

Note 1:apartment, the System queues component calls through hidden window messages, so we can temporarily leave out synchronization issues. Note that it is temporary ha.

NOTE 2: The dual interface means that both the custom interface and the IDispatch interface are supported in one interface. Later, later, will speak. Because the dual interface is very important, we will speak everyday, every night, often speaking------abbreviated as "three talk":)

Note 3: There are 2 ways to reuse a component, aggregation and containment.

Note 4: The function of the name is very nice, but Microsoft has not implemented it at all.

Note 5: These are the concepts in the IDL file, and what will be introduced later.

Design and application of "reprint" COM component (v)--write the first component in ATL

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.