COM component design and application 1 - origin and composite file

xiaoxiao2021-03-18  223

I. Foreword AD a night in 1955, a night of night, my teacher told me: "Xiao Yang, after writing the procedure, as a wooden wood. You have learned some OLE technology. ... ", I was thinking in my heart:" What is joke? Is it a wooden way to write a program? After 100 years ... ", but as a good student, I started "Touch" (Note 1) in the bookstore (Note 2). I have not worried about my heart, I finally bought my first COM book "OLE2 Advanced Programming Technology". This more than 800 pages of big cloth spent me 1/5 monthly salary ... so start a day and night ..... Kung Fu pays off, I insist on reading all the works, I feel: this book, what is it? Kung Fu pays off, I finished reading a big cloth again, I feel: cough ~~~, I don't understand! Kung Fu pays off, I will, I will read again ... I feel: Oh ~~~, I read a little bit, hahaha. ...... ... Kung Fu pays off, I finally, I finally understood. On the 800-page book, I am now useful for 10 pages. At this time, I really appreciate what is the truth of "the book more reading". Later, there are more books that can be bought, and the Internet is also more convenient and cheaper ... In order to make friends on vckbase, no longer experience my pain, no longer repeat my "no head" The hardships of exploration, for the vigorous development of vckbase, for the soaring in China's software career (bad, blowing too high) ... I intend to save some time, write a series of papers, write a series of papers, Just call "COM component design and application". Today is the first part - origin. Second, the storage of documents 350 years ago, Newton was smashed by Apple, so he found that inertiality. But now, the present, any technology inventions and development, no longer rely on the saints of the spirit of Linguang. The advancement of technology is driven by the needs of the society, the interests of the business, the pressure of competition, the penetration of the industry. Microsoft's component technology on the Windows platform is no exception, and its invention has its necessity. What is this factor? The answer is - the storage of files. Open the notepad program, after entering an article, save. - Such a file called "Non-Structured Document"; Open the spreadsheet program, enter a class of student names and test scores, save. - Such files are called "standard structured files"; in our program, you need to write specific data to files in a certain structure and order. - Such files are called "custom structured files"; (such as * .bmp file) The above three types of files, everyone see more. Then the file storage relies on the above way to meet all application needs? Well ~~~, at least 50 years from the computer invented in the computer, it has been enough. Hey, look at the driving role of business interests, what changes have been made to the storage form of the document. Friends over the age of 30, I estimate that I have used the following famous software: WordStar (English editing software under the monologue DOS), WPS (伯 君 written Chinese editing software, it is said that the market share of the year is as high as 90%, each Computer training class for compulsory courses), Lotus-123 (spreadsheet software from Lotus Company) ... Microsoft successfully launched Windows 3.1, began to weary desktop office automation software.

Microsoft's Office development department, each group independently developed Word and Excel and other software, and use "custom structure" to store files. Under the fierce market competition, in order to defeat the competitor, Microsoft naturally generate a thought ------ If I can embed Excel in the Word program, then the user does not buy my Word software. Is it necessary to buy Lotus-123? ! "Virus" (China Microsoft's comrades saw this word, don't be excited, I am adding quotation) The plan is generated, they start implementing the work, this is the origin of the COM's predecessor OLE (Note 3). But immediately encountered a serious technical problem: you need to save the DOC file generated by Word and the XLS file generated by Excel. Solution Advantages Disadvantages create a subdirectory, store the DOC, XLS in this same subdirectory. Data is isolated, Word does not have to understand the storage structure of Excel; it is easy to expand. The structure is too loose, and it is easy to cause damage or loss of data. Not easy to carry. Modify the file storage structure, expand the structure of the inclusive XLS on the basis of the DOC structure. The structure is close, easy to carry and unify management. Word developers need to know the Excel's storage format; lack of scalability, can always expand the structure? !

The above two programs have serious defects, how to solve it? If there is a new solution, you can combine the advantages of the first two programs, eliminate the disadvantage, how good ... Microsoft is a disk operating system, so they naturally present a very perfect design. Solution, that is, transplant the management of disk files into the file ------ composite file, commonly known as "file system in" file ". Even Microsoft did not think of this year, as a simple idea, actually evolved the method of COM component programming. It can be said that the composite file is the cornerstone of COM. The following figure is a scalability method with a composite file organization method. The graph is mapped: Figure 1. On the left indicates a file organization method under a disk, the right side represents a data organization inside the composite file. Third, the characteristics of composite files

The inside of the composite file is managed using a tree constructed in the pointer. Be careful when writing a program, because the one-way pointer is used, so when the positioning operation is used, the rear positioning is fast to position forward; the "stream object" in the composite file is the space that actually saves the data. Its storage unit is 512 bytes. That is, even if you only save one byte data in the stream, it also occupies 512 bytes of file space. Ah ~~~, this is too wasteful? Do not waste! Because the file is saved on disk, even if one byte also takes up a "cluster" space, different processes, or different threads of the same process can be accessed at the same time, and do not interfere with each other; everyone There is such an experience that when you need to insert a byte into a file, you need to operate the entire file, very cumbersome and low efficiency. Composite files provide a very convenient "incremental access" capability; when the file is frequently deleted, the disk space will change very zero, you need to use the disk finishing tool to re-integrate. It is very similar to disk management, and the composite file will also generate this problem. It also needs to be organized when appropriate, but it is relatively simple, as long as a function can be completed.

Fourth, browse the composite file VC6.0 with a tool software "Composite Document Browser", the file name is "VC Directory /common/toOLS/dfview.exe". To facilitate the use of this program, you can add it to the Tools menu. The method is: Tools / Customize ... / Tools card adds new projects. To run dfview.exe, you can open a composite file to observe (Note 4). But strangely, in Microsoft Visual Studio .Net 2003, I can't find this tool program, sweat! However, this will give you an opportunity to practice. After you read this article and master the programming method, write a "Composite Document Browse Editor" program, and practical value. 5. The function of the composite file function composite file is very similar to the operation of the disk directory file. All these functions are divided into three types: WIN API global function, store iStorage interface functions, stream iStream interface functions. What is an interface? What is an interface function? In the future, you will be introduced again. Here everyone can see the "interface" as a function set that completes a set of related operation functions.

WIN API Function Function Description STGCREATEDOCFILE () Create a composite file to get the root storage object stgopenStorage () Open a composite file to get the root storage object stgisstorageFile () determines whether a file is a composite file iStorage function function Description CreateStorage () in the current storage Create a new store, get the sub-storage object createStream () creates a new stream in the current storage, obtain the flow object openStorage () open sub-storage, get the sub-storage object openstream () open flow, get the flow object COPyto () copy store all Objects to target storage, the function can implement the function of "finishing files, release debris space" MOVEELEMENTTO () Mobile Object to Target Storage DestoryElement () Remove Object RenameElement () Rename Object Enumelements () Enumerates All of the current storage Object SETELEMENTTIMES () Modify Time setClass () creates a special stream object in the current store to save CLSID (Note 5) STAT () gets the system information in the current storage Release () Close Storage Objects ISTREAM Function Description The read () reads the data WRITE () in the stream to the stream to set the SEK () to set the stream size. If you know in advance, then call this function first, you can improve performance COPYTO () copy stream data to another stream object () gets the system information clone in the current stream cloned a stream object, which is convenient for different modules in the program. Operation Same Stream Object Release () Close Flow Object WIN API Supplementary Function Description WriteClassSTG () Write CLSID to Storage, Read the WriteClassSTG () written with ISTRAGE: SetClass () readclassstg (), is equivalent to simplified call IStorage :: stat () WriteClassstm () Write CLSID to Started Start Location ReadClassSTM () Read WriteClassSTM () WriteClassSTM () WriteFmTusertypestg () Write the user-specified clipboard format and name to store readfmtusertypestg () read WritefmTusertypestg Write information. Convenient application quickly determines whether it is the format data it needs. CreatestReamonhglobal () memory handle Hglobal converted to stream object gethglobalfromstream () Gets the memory handle used in CreateStreamonhglobal () call In order to make everyone browse and master basic methods, the functions listed above are not all, I omitted "transaction" function And the unrealistic part. For more comprehensive introduction, please read MSDN. The following sequences demonstrate some basic function functions and call methods. Example 1: Create a composite file and establish a sub-storage under this sub-storage, and write data.

void samplecreatedoc ()

{

:: Coinitialize (NULL); // COM initialization

// If it is an MFC program, you can use AFXoleinit () replacement

HRESULT HR; / / Function Performs Return Value

IStorage * pstg = null; // root storage interface pointer

IStorage * psub = null; // sub-storage interface pointer

ISTREAM * PSTM = NULL; // Slow port pointer

hr = :: strgcreatedocfile (// Establish a composite file

L "c: //a.stg", // file name

STGM_CREATE | STGM_WRITE | STGM_SHARE_EXCLUSIVE, // Open mode

0, // Reserved Parameters & PSTG); // Take the root storage interface pointer

Assert (Succeeded (HR)); // In order to highlight the key, simplify the program structure, the assertion is used.

/ / Use condition judgment and exception handling in the actual program

HR = PSTG-> CreateStorage (// Create sub-storage

L "subsstg", // sub-storage name

STGM_CREATE | STGM_WRITE | STGM_SHARE_EXCLUSIVE,

0, 0,

& psub); // Acquire sub-storage interface pointer

Assert (ac));

HR = psub-> createstream (// set a stream

L "STM", // flow name

STGM_CREATE | STGM_WRITE | STGM_SHARE_EXCLUSIVE,

0, 0,

& PSTM); // Take the flow interface pointer

Assert (ac));

HR = PSTM-> WRITE (// write data in the stream

"Hello", // data address

5, // byte length (note, no writing "/ 0)

NULL); // Do not need to get the byte length of the actual written

Assert (ac));

IF (PSTM) PSTM-> release (); // Release stream pointer

IF (PSUB) PSUB-> release (); // Release sub-storage pointer

IF (PSTG) PSTG-> Release (); // Release root storage pointer

:: Couninitialize () // COM release

// If you use AFXoleinit (), the function is not called

}

Figure 2, running sample programs, using dfview.exe to open the effect of observation of the composite file

Example 2: Open a composite file, enumerate all objects below its root store.

#include // ANSI, MBCS, Unicode conversion

void sampeenum ()

{/ / Suppose you have already done COM initialization

LPCTSTR LPFILENAME = _T ("c: //a.stg");

HRESULT HR;

IStorage * PSTG = NULL;

Uses_conversion; // (Note 6)

LPColestr LPWFILENAME = T2Cole (lpfilename); // Convert T type is a wide character

HR = :: strgisstoragefile (lpwfilename); // Is it a composite file?

IF (Failed (HR)) Return;

hr = :: strgopenStorage (// Open the composite file

LPWFILENAME, / / ​​file name

NULL,

STGM_READ | STGM_SHARE_DENY_WRITE,

0,

0,

& PSTG); // Get root storage interface pointer

IEnumstatstg * penum = null; // enumerator

HR = PSTG-> ENUMELEMENTS (0, NULL, 0, & PENUM);

Assert (ac));

STATSTG STATSTG;

While (noerror == penum-> Next (1, & statsTG, null))

{

// statsTG.Type Save Object Type STGTY_STREAM or STGTY_STORAGE

// statstg.pwcsname Save the object name

// ...... There are still many information such as time, length. Check out msdn :: cotaskmemfree (statstg.pwcsname); // Release the memory used by the name (Note 6)

}

IF (Penum) Penum-> Release ();

IF (PSTG) PSTG-> Release ();

}

Sixth, small knot

Composite files, structured storage, is the origin of Microsoft component ideas. On this basis, continue to develop continuous, naming, Activex, object embedding, on-site activation ... a series of new technologies, new concepts. So understanding

with

Mastering the composite file is very important, even if there is no comprehensive use of component technology in your program, the composite file technology can be applied separately. I wish you all a happy study, struggle for socialist software career :-)

Keep your homework ...

Job 1: Write a small app, extract additional information from the MSWORD DOC file (author, company ...).

Job 2: Write a full-featured "Composite Document Browse Editor".

Note 1: Xuemo, verb, northern dialect, find the meaning of search.

Note 2: Q: Why don't you check your information?

A: What to open an international joke! In that far in the 1995, my 500 wages didn't eat, I didn't eat, I didn't drink, just enough to 100 hours.

Note 3: OLE, the connection and embedding of objects.

Note 4: You can open the MswView.exe to open the MSWORD DOC file for browsing. However, the program does not achieve internationalization, and cannot open the Chinese file name composite file, so it is necessary to change the name to browse.

Note 5: CLSID, introduced in subsequent articles.

Note 6: About the problem of memory usage in COM, introduced in subsequent articles.

转载请注明原文地址:https://www.9cbs.com/read-129946.html

New Post(0)