COM Component Design and Application (1)

Source: Internet
Author: User

COM Component Design and Application (1)
Origin and composite File

Author: Instructor Yang

I. Preface

On a dark night in 1995 AD, one of my teachers said to me, "Xiao Yang, I will write programs in the future, just like building blocks. Hurry up and learn some ole technologies... ". At that time, I thought," Are you kidding me? How do I build blocks to write programs? In May 100 ...... ", but as a good student, I started to" Touch "(Note 1) Ole-related books in the bookstore (note 2 ). I finally bought my first com book ole2 advanced programming technology, which cost 800 of my monthly salary for more than 1/5 pages ...... so I started day and night farming .....
I insist on reading all the books. What is this book talking about?
I have read the story again. My feeling is: Cough ~~~, No!
Hard work pays off, I will, I will, and I will read again... feeling: Oh ~~~, I have read a little bit, hahaha.
............
I finally understand it.
The 800-page book is actually useful to me as many as 10 pages. At this time, I realized what the reason is "the book reads thinner and thinner. Later, I had more books to buy, and it was more convenient and cheaper to access the Internet ......

In order to let my friends on vckbase no longer experience the hardships I 've ever experienced, I don't want to repeat the hardships I 've been exploring like a "no-head fly", I want to make vckbase flourish, and take off for the Chinese software business (bad, too high )...... I plan to save some time to earn points on BBS and write a series of papers. This is called "COM component design and application. Today is the first part -- origin.

Ii. File Storage

It is said that Newton was beheaded by an apple before 350, so he found the universal gravitation. But now in the 21st century, the invention and development of any technology no longer rely on the flash of the sage. Technological advances have been promoted by social needs, commercial interests, competitive pressures, and industry penetration. Microsoft's component technology on Windows is no exception. Its Invention has its own inevitable factors. What is this? The answer is: file storage.
Open the Notepad program, enter an article, and save it. -- Such a file is called an unstructured file ";
Open the workbook program, enter the name and score of the student in the class, and save. -- Such a file is called a standard structured file ";
In the program we write, specific data needs to be written to the file in a certain structure and order for storage. -- Such a file is called a "Custom structured file" (for example, *. BMP file)
For more information about the above three types of files, see. Does NAs meet all application requirements based on the above methods? ~~~, It has been enough for at least 50 years since the invention of the computer. Hey, let's take a look at the promotion effect of commercial interests and what changes have taken place in the form of file storage. A friend over 30 years old, I guess I have used the following famous software before: WordStar (the English editing software under Duba DoS) and WPS (the Chinese editing software written by Chu bojun, it is said that the market share of the year was as high as 90%, and various required courses for computer training courses), lotus-123 (spreadsheet software produced by Lotus )......
After Microsoft successfully launched Windows 3.1, it began to covet the desktop office automation software field. Microsoft's Office Development Department, each group independently developed software such as Word and Excel, and used a "Custom structure" to store files. In the fierce market competition, Microsoft naturally came up with the idea that to defeat its competitors, if I could embed an Excel file in a word program, so when the user buys my word software, there is no need to buy another lotus-123 ?! After the "vicious" (Chinese Microsoft comrades saw this word, don't be excited. I added quotation marks) program, they started implementation, this is the origin of OLE, the predecessor of COM (note 3 ). However, we immediately encountered a serious technical problem: we need to save the DOC file generated by word and the xls file generated by Excel together.
 

Solution

Advantages

Disadvantages

Create a sub-directory and store Doc and XLS in the same sub-directory. Data isolation is good, word does not need to understand the storage structure of Excel; it is easy to expand. The structure is too loose and may cause data damage or loss.
Not easy to carry.
Modify the file storage structure and extend the XLS-Tolerant Structure Based on the doc structure. Tightly structured, easy to carry, and unified management. Developers of word need to be familiar with the Excel storage format. If there is no extensibility, can they simply extend the structure without adding a new type ?!

Both of the above solutions have serious defects. How can this problem be solved? If you have a new solution, you can combine the advantages of the first two solutions to eliminate the disadvantages. How good is it ...... microsoft started out as a disk operating system, and naturally they proposed a perfect design solution, that is, migrating the disk file management method to the file ------ composite file, commonly known as "File System in a file ". Even Microsoft did not think of it that year. With such a simple idea, the COM component programming method was finally developed. Composite files are the cornerstone of COM. It is an analogy between the disk file organization mode and the composite file organization mode:

Figure 1. The left side shows the file organization mode under a disk, and the right side shows the internal data organization mode of a composite file.

Iii. Features of composite files

  1. The composite file is internally managed by a tree constructed using pointers. When writing a program, you should note that the one-way pointer is used, so the backward positioning is faster than forward positioning when performing a positioning operation;
  2. The "stream object" in the composite file is the space for truly saving data. The storage unit is 512 bytes. That is to say, even if you store only one byte of data in the stream, it occupies 512 bytes of file space. Ah ~~~, Is it too wasteful? No waste! Because the files are stored on the disk, even one byte will occupy a "cluster" space;
  3. Different processes, or different threads of the same process, can simultaneously access different parts of a composite file without interfering with each other;
  4. Everyone has this experience. To insert a byte into a file, you need to operate the entire file, which is cumbersome and inefficient. Composite files provide very convenient "incremental access" capabilities;
  5. When files are frequently deleted and copied, the disk space becomes fragmented and needs to be reintegrated using the disk sorting tool. Similar to disk management, composite files also cause this problem and need to be sorted out when appropriate. However, it is relatively simple to call a function.

4. Browse composite files

Vc6.0 comes with a tool software "Composite File Browser" named "VC directory \ common \ tools \ dfview.exe ". To facilitate the use of this program, you can add it to the Tools menu. Add a new project to the tools \ customize... \ tools card. Run dfview.exe to open a composite file (note 4 ). However, in Microsoft Visual Studio. NET 2003, I couldn't find the tool! However, this just gives you a chance to practice. After you have read this article and mastered the programming method, you can write a "composite File Browser Editor" program and practice it again, there are also practical values.

V., Composite file functions

The function of the composite file is similar to that of the disk directory file. All these functions are divided into three types: win api global functions, store istorage interface functions, and stream istream interface functions. What is an interface? What is an interface function? Later articles will be introduced one after another. Here we only need to regard the "interface" as a set of functions for completing a set of related operation functions.
 

Win API functions

Function Description

Stgcreatedocfile () Create a composite file to obtain the root storage object
Stgopenstorage () Open a composite file to obtain the root storage object.
Stgisstoragefile () Determine whether a file is a composite File

 

Istorage Function

Function Description

Createstorage () Create a new storage in the current storage to obtain the sub-storage object
Createstream () Create a new stream in the current storage to obtain the stream object.
Openstorage () Open the sub-storage to obtain the sub-storage object.
Openstream () Open the stream to get the stream object.
Copyto () Copy all objects in the storage to the target storage. This function can be used to "Sort files and release fragments ".
Moveelementto () Move objects to target Storage
Destoryelement () Delete object
Renameelement () Rename an object
Enumelements () Enumerate all objects in the current storage
Setelementtimes () Time when the object was modified
Setclass () Create a special stream object in the current storage to save the CLSID (note 5)
Stat () Obtain system information in the current storage
Release () Disable storage objects
 

Istream Function

Function Description

Read () Read data from the stream
Write () Write Data to the stream
Seek () Locate read/write locations
Setsize () Set the stream size. If you know the size in advance, you can call this function to improve the performance.
Copyto () Copy stream data to another stream object
Stat () Obtain system information in the current stream
Clone () Clone a stream object to allow different modules in the program to operate on the same stream object.
Release () Close Stream Object
 
Win api supplement Function Function Description
Writeclassstg () Write CLSID to storage, same as istorage: setclass ()
Readclassstg () Read the CLSID written by writeclassstg (), which is equivalent to simplifying the call of istorage: Stat ()
Writeclassstm () Write CLSID to the starting position of the stream
Readclassstm () Read the CLSID written by writeclassstm ().
Writefmtusertypestg () Write the clipboard format and name specified by the user to the storage
Readfmtusertypestg () Read the information written by writefmtusertypestg. It is convenient for the application to quickly determine whether the data is in the format required by the application.
Createstreamonhglobal () Memory handle hglobal to stream object
Gethglobalfromstream () Obtains the memory handle used in the createstreamonhglobal () call.

In order to allow everyone to quickly browse and master the basic methods, not all of the functions listed above, I omitted the "transaction" function and the unimplemented function section. For more information, see msdn.
The following program snippet demonstrates some basic function functions and call methods.
Example 1: Create a composite file, create a sub-store under it, create another stream in the sub-store, and write data.

Void samplecreatedoc () {: coinitialize (null); // COM Initialization // if it is an MFC program, you can use afxoleinit () to replace hresult hr; // function execution return value istorage * pstg = NULL; // The root storage interface pointer istorage * psub = NULL; // The Sub-storage interface pointer istream * PSTM = NULL; // stream interface pointer hR =: stgcreatedocfile (// create a composite file l "C: \. STG ", // file name stgm_create | stgm_write | stgm_clu_exclusive, // open mode 0, // retain parameter & pstg ); // obtain the root storage interface pointer assert (succeeded (HR); // assertions are used to highlight the key and simplify the program structure. // In the actual program, use condition judgment and Exception Handling hR = pstg-> createstorage (// create sub-storage l "substg ", // sub-storage name stgm_create | stgm_write | stgm_clu_exclusive, & psub); // obtain the sub-storage interface pointer assert (succeeded (HR )); hR = psub-> createstream (// create stream l "stm", // stream name stgm_create | stgm_write | stgm_clu_exclusive, 0, & PSTM ); // obtain the stream interface pointer assert (succeeded (HR); HR = PSTM-> write (// write data "hello" to the stream, // data address 5, // byte length (Note: \ 0 at the end of the string is not written) null); // you do not need to obtain the actual written byte length assert (succeeded (HR); If (PSTM) PSTM-> release (); // release the stream pointer if (psub) psub-> release (); // release the sub-storage pointer if (pstg) pstg-> release (); // release the root storage pointer: couninitialize () // com release // If afxoleinit () is used, this function is not called}


Figure 2. Run sample program 1 and use dfview.exe to open and observe

Example 2: open a composite file and enumerate all objects under its root storage.

# Include <atlconv. h> // ANSI, MBCS, and Unicode conversion void sampleenum () {// assume that you have initialized the lptstr lpfilename = _ T ("C: \. STG "); hresult hr; istorage * pstg = NULL; uses_conversion; // (note 6) lpcolestr lpwfilename = t2cole (lpfilename); // converts T type to wide character hR = :: stgisstoragefile (lpwfilename); // is it a composite file? If (failed (HR) return; HR =: stgopenstorage (// open the compound file lpwfilename, // the file name is null, stgm_read | stgm_share_deny_write, 0, 0, & pstg ); // obtain the root storage interface pointer ienumstatstg * penum = NULL; // the enumerator hR = pstg-> enumelements (0, null, 0, & penum ); assert (succeeded (HR); statstg; while (noerror = penum-> next (1, & statstg, null) {// statstg. type stores the object type stgty_stream or stgty_storage // statstg. pwcsname stores the object name //...... time, length, etc. A lot of information. Please refer to msdn: cotaskmemfree (statstg. pwcsname); // release the memory used by the name (note 6)} If (penum) penum-> release (); If (pstg) pstg-> release ();}

Vi. Summary

Composite files and structured storage are the origins of Microsoft's component ideas. On this basis, they continue to develop persistence, naming, ActiveX, object embedding, and on-site activation ...... A series of new technologies and new concepts. Therefore, it is very important to understand and master the composite file. Even if you do not fully use the component technology in your program, the composite file technology can be applied independently. I wish you all a happy learning experience and strive for the socialist software business :-)

Leave homework ......
Job 1: Write a small application, extract additional information (author, company...) from the MSWord DOC file ......).
Job 2: write a full-featured "Composite File Browser Editor ".

Note 1: xuemo, verb, northern dialect, search for meaning.
NOTE 2: Q: Why don't I go online to learn more?
A: Are you kidding me! In the distant 1995 s, my 500 yuan salary was enough for an Internet network of just 100 hours.
NOTE 3: Ole: Object connection and embedding.
Note 4: You can use dfview.exe to open the DOC file of MSWord to browse the composite file. However, this program is not internationalized and cannot open a composite file with a Chinese file name. Therefore, you need to change the name before browsing.
Note 5: CLSID, which will be introduced in subsequent articles.
Note 6: For memory usage in COM, refer to the subsequent articles.

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.