COM Component Design and Application (6)

Source: Internet
Author: User

COM Component Design and Application (6)
Use ATL to write the first component

Author: Instructor Yang

Download source code

I. Preface

1. It is basically consistent with the content in COM Component Design and Application (5. However, this article explains how to use it in vc.net 2003. Even if you no longer use vc6.0, compare it with the previous one.
2. Except for the iunknown interfaces required by all COM components, the first component implements a self-defined interface ifun, which has two functions: add () completes the addition of two values, and CAT () completes the connection between the two strings.
3. Let's hear it! Started :-)
 

II,Create an ATL Project

Step 2.1: create a solution.
Step 2.2: In this solution, create a VC ++ ATL Project. The sample program is simple2 and the DLL method is selected. See figure 1 and figure 2.


Figure 1. Create an ATL Project


Figure 2. Select a non-attribute DLL component type

  Attribute-basedAttribute-based programming is the future direction, but we should not select it now.
  Dynamic link library (DLL)Select it.
  Executable File (exe)I will talk about it later.
  Service (exe)Creates a system service component program, which is loaded and executed after the system is started.
  Allow merging proxy/stub (stub) CodeIf this option is selected, the "Proxy/stub" code is merged into the component program. Otherwise, you must compile the Code separately and register the proxy stub program separately. Proxy/stub. What is this concept? Do you remember what we introduced in the previous book? When the caller calls the functions of external or remote components, the proxy/stub is responsible for data exchange. Let's talk about the specific change and operation of proxy/stub ......
  SupportedMFCUnless for a special reason, we should write the Atl program. It is best not to select this option. You may say that, without the support of MFC, what should you do with cstring? Let me tell you a secret. I don't tell anyone, so I will live with this secret for the rest of my life:
1. Do you know STL? It can be replaced by string in STL;
2. Write a mystring class by yourself;
3. quietly and secretly, do not tell others (especially don't tell Microsoft), and use the cstring source code in MFC;
4. Using the ccombstr class can at least simplify string operations;
5. directly use APIs to operate strings. When we all learn the C language, we start from here. (Not to mention, huh, huh)
  Support for COM + 1.0Supports the COM + function of transaction processing. COM + may be introduced back in 99th.

3. Add an ATL Object Class

Step 3.1: Choose "project \ add class..." (or right-click the project and choose "add \ add class...") and select an ATL simple object. See figure 3.


Figure 3. Create an ATL Simple Object

In addition to simple objects (only implementing the iunknown Interface), you can also select the "ATL control" (ActiveX, implementing more than 10 interfaces )...... you can select many component object types, but in essence, it is to let the wizard add some interfaces for us by default. In future articles, I will introduce them one after another.

Step 3.2: Add a custom cfun (interface ifun), as shown in figure 4.

 
Figure 4. Enter a name

In fact, we only need to enter the abbreviation, and other projects will be automatically entered. There is nothing to say, just pay attention to the progid item. The default progid construction method is "project name. Abbreviation name ".

Step 3.3: Fill in the interface property options, as shown in Figure 5.


Figure 5 Interface Options

  Thread ModelCom thread, I think it is the most annoying and complex part. The concept of COM thread and apartment will be provided for further introduction. Now all of us choose "unit" (apartment). What does it mean? Simply put, when a component function is called in a thread, these calls are queued. Therefore, in this mode, we do not need to consider synchronization for the moment. (Note 1)
  Interface. Dual (dual), which is very important and very commonly used, but we will not talk about it today (note 2 ).Remember! Remember! In our first com program, you must select "Custom "!!!!(If you have selected an error, delete all the content and try again .)
  AggregationWhether the components we write can be aggregated by others (note 3) in the future. "Can only be created as aggregation" is a bit similar to the pure virtual class in C ++. If you are a chief engineer, you should select it only for designing but not writing code yourself.
  IsupporterrorinfoWhether error handling interfaces with rich information are supported. I will talk about it later.
  ConnectionPointWhether the connection point interface (event and callback) is supported ). I will talk about it later.
  IobjectwithsiteWhether ie calls are supported

4. Add interface functions


Figure 6. Call up the menu for adding an Interface Method


Figure 7. Add an interface function

Add the add () function and the CAT () function as shown in the following figure. [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 function operation result. A function can have multiple [in] and [out], but [retval] can only have one, and it must be combined with [out] and placed in the last position. (Note 4)


Figure 8. Illustration after interface function definition

We all know that to change class functions in C ++, we need to modify two places: header file (. h) class function declaration. The second is the function body (. CPP) file implementation. Now, if we use ATL to write component programs, we need to modify the interface definition (IDL) file. Don't worry, IDL will discuss it next time.

5. Implement interface functions

Click the cfun \ base item and the interface \ add (...) in double-Point Graph 8 to start the input function implementation:

STDMETHODIMP CFun::Add(long n1, long n2, long *pVal){*pVal = n1 + n2;return S_OK;}

This is too simple, and it is no longer a waste of words ". Below we implement the CAT () function for string connection:

Stdmethodimp cfun: CAT (BSTR S1, BSTR S2, BSTR * pval) {int nlen1 =: sysstringlen (S1); // The length of S1 is int nlen2 = :: sysstringlen (S2); // S2 character length * pval =: sysallocstringlen (S1, nlen1 + nlen2 ); // construct a new BSTR and save S1 to 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 completed by calling the basic API.
Teacher: Yes. To be honest, it's really tricky.
Student: We use memcpy () to connect the second string. Why not use the wcscat () function?
INSTRUCTOR: it is acceptable in most cases, but you need to know that BSTR contains a string length, so the actual BSTR string content can store l'' \ 0, however, the wcscat () function uses l'' \ 0'' as the end mark of replication, which may cause data loss. Do you understand?
Student: understand, understand. After reading "Data Type of COM Component Design and Application (3)", I will understand it. Is there any simple way, teacher?
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! Using ccombstr is much simpler. What is the difference between ccombstr: Copy () and ccombstr: Detach?
INSTRUCTOR: ccombstr: Copy () will make a copy of BSTR. In addition, ccombstr: copyto () has similar functions. Ccombstr: Detach () is to strip the object from the internal BSTR pointer. This function is a little faster because there is no replication process. However, you must note that this object cannot be used once it is stripped.
Student: teacher, you are talking too well. I admire you for your respect, such as the mountains and mountains ......
Instructor: Stop, stop! Leave homework ......
1. Write this component according to the content described today;
2. Whether you understand it or not, observe the IDL file and CPP file;
3. What files are generated after compilation? If it is a text file, open it;
4. Download the sample program (vc.net 2003) in this article to compile and run it. Then, preview the call methods in the sample program;
Student: You know, class is coming soon. I want to go to the bathroom. I can't hold it down ......
INSTRUCTOR: class! Don't forget to post my post ......

Vi. Summary

This section describes how to create the first ATL component program and how to use this component. Please pay attention to "COM Component Design and Application (7)".

NOTE 1: The Apartment system queues component calls through hidden window messages, so we can temporarily ignore the synchronization issue. Note: It is temporary.
Note 2: The dual interface indicates that both the custom interface and the idispatch interface are supported in an interface. Later, later. Because dual interfaces are very important, we will talk about them every day, night, and often ------ "Three Stresses" for short ":)
NOTE 3: There are two reuse methods for components, aggregation and inclusion.
Note 4: these are concepts in the IDL file. We will introduce what will be used in the future.

Source: http://www.vckbase.com/document/viewdoc? Id = 1498

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.