THE Delphi Object Model (Part III)

zhaozj2021-02-11  182

THE Delphi Object Model (Part III)

Sample Chapter of Delphi in A NutshellProduct:

Delphi All Versions

Category: Oo-RelatedSkill Level: Scoring: Last Update: 05/21 / 2000Search Keys: Delphi Delphi3000 Article Object Model OOP InterfaceStimeS Scored: 11Visits:

4947

Uploader: Stefan Walthercompany: Bluestep.com It-ConsultingReference: ray Lischner - O "REILLY Question / Problem / Abstract:

Delphi's support for object-oriented programming is rich and powerful. In addition to traditional classes and objects, Delphi also has interfaces (similar to those found in COM and Java), exception handling, and multithreaded programming. This chapter covers Delphi's object model in depth YOULD Already Be Familiar With Standard Pascal and general Principles of Object-Oriented Programming.

Answer: Reprinted with permission from O'Reilly & Associates Messages You should be familiar with Windows messages: user interactions and other events generate messages, which Windows sends to an application An application processes messages one at a time to respond to the user and other. events. Each kind of message has a unique number and two integer parameters. Sometimes a parameter is actually a pointer to a string or structure that contains more complex information. Messages form the heart of Windows event-driven architecture, and Delphi has a unique way of supporting Windows messages In Delphi, every object -. not only window controls -.. can respond to messages A message has an integer identifier and can contain any amount of additional information In the VCL, the Application object receives Windows messages and maps In Other Words, Windows Messages Are A Special Case Of More General Delphi Messages. A Delphi Message Is A Record Where The First two bytes contain an integer message identifier, and the remainder of the record is programmer-defined. Delphi's message dispatcher never refers to any part of the message record past the message number, so you are free to store any amount or kind of information in a message record. By convention, the VCL always uses Windows-style message records (TMessage), but if you find other uses for Delphi messages, you do not need to feel so constrained. to send a message to an object, fill in the Message Identifier and Call The Object's Dispatch Method. Delphi Looks Up The Message Number in The Object '

s message table. The message table contains pointers to all the message handlers that the class defines. If the class does not define a message handler for the message number, Delphi searches the parent class's message table. The search continues until Delphi finds a message handler . or it reaches the TObject class If the class and its ancestor classes do not define a message handler for the message number, Delphi calls the object's DefaultHandler method window controls in the VCL override DefaultHandler to pass the message to the window procedure.;

other classes usually ignore unknown messages. You can override DefaultHandler to do anything you want, perhaps raise an exception. Use the message directive to declare a message handler for any message. See Chapter 5 for details about the message directive. Message handlers use the same message table and dispatcher as dynamic methods. Each method that you declare with the dynamic directive is assigned a 16-bit negative number, which is really a message number. A call to a dynamic method uses the same dispatch code to look up the dynamic method , but if the method is not found, that means the dynamic method is abstract, so Delphi calls AbstractErrorProc to report a call to an abstract method. Because dynamic methods use negative numbers, you can not write a message handler for negative message numbers, that is Message NumBers with the Most-Significant Bit Set To One. this Limitation Should Not Cause Any Problems For Normal Applications. If You Need To Define Custom Messages, You Have TH e entire space above WM_USER ($ 0F00) available, up to $ 7FFF. Delphi looks up dynamic methods and messages in the same table using a linear search, so with large message tables, your application will waste time performing method lookups. Delphi's message system is entirely general purpose, so you might find a creative use for it. Usually, interfaces provide the same capability, but with better performance and increased type-safety. Memory Management Delphi manages the memory and lifetime of strings, Variants, dynamic arrays, and Interfaces Automatic or. for All Other Dynamically Allocated Memory, You - The Programmer - Are IN Charge. IT '

s easy to be confused because it seems as though Delphi automatically manages the memory of components, too, but that's just a trick of the VCL. Components Versus Objects The VCL's TComponent class has two fancy mechanisms for managing object lifetimes, and they often confuse new Delphi programmers, tricking them into thinking that Delphi always manages object lifetimes. It's important that you understand exactly how components work, so you will not be fooled. Every component has an owner. When the owner is freed, it automatically frees the components that it owns. A form owns the components you drop on it, so when the form is freed, it automatically frees all the components on the form. Thus, you do not usually need to be concerned with managing the lifetime of forms and components. WHEN A Form or Component Frees A Component It Owns WHETHER IT HAS A Published Field of The Same Name As The Component. If So, The Owner Sets That Field To Nil. Thus, if Your Form Dynami cally adds or removes components, the form's fields always contain valid object references or are nil. Do not be fooled into thinking that Delphi does this for any other field or object reference. The trick works only for published fields (such as those automatically created WHEN You Drop A Component On A Form in The Ide's Form Editor

s classes or functions to create the threads. If you go straight to the Windows API and the CreateThread function, you must set the IsMultiThread variable to True. For more information, see Chapter 4, Concurrent Programming. Ordinarily, when you construct an object, Delphi calls NewInstance to allocate and initialize the object. you can override NewInstance to change the way Delphi allocates memory for the object. for example, suppose you have an application that frequently uses doubly linked lists. Instead of using the general-purpose memory allocator for every node, it's much faster to keep a chain of available nodes for reuse. Use Delphi's memory manager only when the node list is empty. If your application frequently allocates and frees nodes, this special-purpose allocator can be faster than the general-purpose Allocator. EXAMPLE 2-17 Shows A Simple Implementation of this Scheme (see Chapter Version of this class.) EXAMPLE 2-17: Custom Memory Management For Linked Lists TypetNode = Class

Private

FNEXT, FPREVIOS: TNODE;

protected

// Nodes Are Under Control of TlinkedList.

Procedure Relink (NewNext, NewpRevious: TNode);

Constructor Create (Next: TNODE = NIL; Previous: tnode = nil);

PROCEDURE Realfree;

public

DESTRUCTOR DESTROY; OVERRIDE;

Class Function Newinstance: TOBJECT; OVERRIDE

Excedure FreeInstance; Override;

Property Next: Tnode Read Fnext;

Property Previous: Tnode Read FPREVIOUS;

END;

// Singly Linked List of Nodes That Are Free for Reuse.

// Only the next fields are buy to maintain this list.

VAR

Nodelist: tnode;

// allocate a new node by getting the head of the nodelist.

// Remember to call InitInstance to Initialize the Node That WAS

// Taken from nodelist.// if the nodelist is Empty, Allocate a node normally.

Class function tnode.newinstance: TOBJECT;

Begin

if nodelist = nil dam

Result: = inherited newinstance

Else

Begin

Result: = nodelist;

Nodelist: = nodelist.next;

InitInstance (Result);

END;

END;

// Because The Nodelist Uses Only the next field, set the prepvious

// field to a special value. if a program erroneouslyly refers to the

// Previous Field of a Free Node, you can see the special value

// and know the cause of the error.

Const

BadpointervaluetoflageRrors = Pointer ($ F0EE0BAD);

// free a node by adding it to the head of the nodelist. This is much

// Faster Than Using The General-Purpose Memory Manager.

Procedure tnode.freeinstance;

Begin

FPREVIOS: = BADPOINTERVALUETOFLAGERRORS;

Fnext: = nodelist;

Nodelist: = Self;

END;

// if you want to clean up the list prot preoprly when the application

// Finishes, Call Realfree for Each Node in the list. The inherited

// FreeInstance Method Frees and cleans up the node for real.

Procedure tnode.realfree;

Begin

Inherited freeInstance;

END;

You can also replace the entire memory management system that Delphi uses. Install a new memory manager by calling SetMemoryManager. For example, you might want to replace Delphi's suballocator with an allocator that performs additional error checking. Example 2-18 shows a custom memory manager that keeps a list of pointers the program has allocated and explicitly checks each attempt to free a pointer against the list. Any attempt to free an invalid pointer is refused, and Delphi will report a runtime error (which SysUtils changes to an exception). As . a bonus, the memory manager checks that the list is empty when the application ends If the list is not empty, you have a memory leak Example 2-18: Installing a Custom Memory Manager unit CheckMemMgr; interface.

Uses windows;

Function Checkget (Size: Integer): Pointer;

Function Checkfree (MEM: POINTER): Integer;

Function CheckRealloc (MEM: POINTER; SIZE: POINTER;

VAR

Heapflags: dword; // in a single-threaded application, you might

// Want to set this to heap_no_serialize.

IMPLEMentation

Const

MaxSize = maxint Div 4;

Type

TPOINTERARRAY = Array [1..maxsize] of pointer;

PPOINTERARRAY = ^ Tpointerarray;

VAR

HEAP: THANDLE; / / Windows Heap for the Pointer List

List: ppointerarray; // list of allocated pointers

Listsize: integer; // Number of Pointers in the list

Listalloc: integer; // Capacity of the Pointer List

// if the list of allocated Pointers Is Not Empty when Program

// Finishes, That Means you have a memory leak. Handling the memory

// Leak is left as an esrcise for the reader.

Procedure memories;

Begin

// Report the Leak to the user, But Remember That The Program IS

// Shutting Down, So you sell probably stick to the windows api // and not use the vcl.

END;

// Add a pointer to the list.

Procedure addmem (MEM: POINTER);

Begin

IF list = nil dam

Begin

// new list of pointers.

Listalloc: = 8;

List: = HeapAlloc (Heap, HeapFlags, Listalloc * Sizeof (Pointer);

end

Else if Listsize> = listalloc the

Begin

// make the list bigger. Try to do it homewhat intelligently.

IF Listalloc <256 THEN

Listalloc: = Listalloc * 2

Else

Listalloc: = Listalloc 256;

List: = HeapRealloc (HEAP, Heapflags, List,

Listalloc * sizeof (Pointer);

END;

// Add a pointer to the list.

INC; LISTSIZE

List [Listsize]: = MEM;

END;

// Look for a Pointer in The List, And Remove It. Return True for

// Success, And False if The Pointer is not in the list.

Function Removemem (MEM: POINTER): Boolean;

VAR

I: integer;

Begin

For i: = 1 to Listsize DO

IF list [i] = MEM THEN

Begin

MoveMemory (@List [i], @List [i 1], (listsize-i) * sizeof (Pointer);

Dec (listsize);

RESULT: = TRUE;

EXIT;

END;

Result: = FALSE;

END;

// Replacement Memory Allocator.

Function Checkget (Size: Integer): Pointer;

Begin

Result: = sysgetmem (size);

AddMem (Result);

END;

// if The Pointer Isn't in the list, don't call the real

// free function. Return 0 for success, and non-zero for an error.

Function Checkfree (MEM: POINTER): Integer;

Begin

IF not removemem (mem) THEN

Result: = 1

Else

Result: = sysfreemem (MEM);

END;

// Remove the old pointer and add the new one, Which might be the

// Same as the old one, or it might be different. Return NIL for

// An Error, And Delphi Will Raise An Exception.

Function CheckRealloc (MEM: POINTER; SIZE: Integer: Pointer; Begin

IF not removemem (mem) THEN

Result: = NIL

Else

Begin

Result: = sysReallocmem (MEM, SIZE);

AddMem (Result);

END;

END;

Procedure setnewmanager;

VAR

Mgr: TMEMORYMANAGER;

Begin

Mgr.getMem: = Checkget;

Mgr.freemem: = Checkfree;

Mgr.reallocmem: = checkrealloc;

SetMemoryManager (MGR);

END;

Initialization

Heap: = HeapCreate (0, Heapflags, 0);

Setnewmanager;

Finalization

IF Listsize <> 0 THEN

MemoryleAk;

Heapdestroy (HEAP);

End.

If you define a custom memory manager, you must ensure that your memory manager is used for all memory allocation. The easiest way to do this is to set the memory manager in a unit's initialization section, as shown in Example 2-18. The memory Management Unit Must Be The First Unit Listed in The Project '

s uses declaration. Ordinarily, if a unit makes global changes in its initialization section, it should clean up those changes in its finalization section. A unit in a package might be loaded and unloaded many times in a single application, so cleaning up is important . A memory manager is different, though. Memory allocated by one manager can not be freed by another manager, so you must ensure that only one manager is active in an application, and that the manager is active for the entire duration of the application. This means you must not put your memory manager in a package, although you can use a DLL, as explained in the next section. Memory and DLLs If you use DLLs and try to pass objects between DLLs or between the application and a DLL, you run into a number of problems. First of all, each DLL and EXE keeps its own copy of its class tables. The is and as operators do not work correctly for objects passed between DLLs and EXEs. Use packages (described in Chapter 1) to solve Thi s problem. Another problem is that any memory allocated in a DLL is owned by that DLL. When Windows unloads the DLL, all memory allocated by the DLL is freed, even if the EXE or another DLL holds a pointer to that memory. This can be a major problem when using strings, dynamic arrays, and Variants because you never know when Delphi will allocate memory automatically. The solution is to use the ShareMem unit as the first unit of your project and every DLL. The ShareMem unit installs a custom memory manager that redirects all memory allocation requests to a special DLL, BorlndMM.dll. The application does not unload BorlndMM until the application exits. The DLL magic takes place transparently, so you don '

t need to worry about the details. Just make sure you use the ShareMem unit, and make sure it is the first unit used by your program and libraries. When you release your application to your clients or customers, you will need to include BorlndMM. dll. If you define your own memory manager, and you need to use DLLs, you must duplicate the magic performed by the ShareMem unit. you can replace ShareMem with your own unit that forwards memory requests to your DLL, which uses your custom memory manager . Example 2-19 shows one way to define your own replacement for the ShareMem unit Example 2-19:. Defining a Shared Memory Manager unit CheckShareMem; // use this unit first so all memory allocations use the shared

// Memory Manager. The Application And All Dlls Must Use this unit.

// You Cannot USE Packages Because Those Dlls Use The Default Borland

// Shared Memory Manager.

Interface

Function Checkget (Size: Integer): Pointer;

Function Checkfree (MEM: POINTER): Integer;

Function CheckRealloc (MEM: POINTER; SIZE: POINTER;

IMPLEMentation

Const

DLL = 'Checkmm.dll';

Function Checkget (SIZE: Integer): Pointer; External DLL;

Function checkfree (MEM: POINTER): Integer; External DLL;

Function CheckRealloc (MEM: POINTER; SIZE: POINTER;

External DLL;

Procedure setnewmanager;

VAR

Mgr: TMEMORYMANAGER;

Begin

Mgr.getMem: = Checkget;

Mgr.freemem: = Checkfree;

Mgr.reallocmem: = checkrealloc;

SetMemoryManager (MGR);

END;

Initialization

Setnewmanager;

End.

.. The CheckMM DLL uses your custom memory manager and exports its functions so they can be used by the CheckShareMem unit Example 2-20 shows the source code for the CheckMM library Example 2-20: Defining the Shared Memory Manager DLL library CheckMM; / / Replacement for borlndmm.dll to use a customer manager.

Uses

Checkmemmgr;

Exports

Checkget, Checkfree, CheckRealloc;

Begin

End.

Your program and library projects use the CheckShareMem unit first, and all memory requests go to CheckMM.dll, which uses the error-checking memory manager. You do not often need to replace Delphi's memory manager, but as you can see, it isn 't difficult to do TIP:. The memory manager that comes with Delphi works well for most applications, but it does not perform well in some cases The average application allocates and frees memory in chunks of varying sizes If your application is different and.. Allocates Memory In Ever-Increasing Sizes (Say, Because You Have A Dynamic Array That Grows in Small Steps to a Very Large Size), Performance Will Suffer. Delphi '

s memory manager will allocate more memory than your application needs. One solution is to redesign your program so it uses memory in a different pattern (say, by preallocating a large dynamic array). Another solution is to write a memory manager that better meets the specialized needs of your application. For example, the new memory manager might use the Windows API (HeapAllocate, etc.). Old-style Object types In addition to class types, Delphi supports an obsolete type that uses the object keyword. Old-style objects exist for backward compatibility with Turbo Pascal, but they might be dropped entirely from future versions of Delphi. Old-style object types are more like records than new-style objects. Fields in an old-style object are laid out in the same manner as in records. If the object type does not have any virtual methods, there is no hidden field for the VMT pointer, for example. Unlike records, object types can use inheritance. Derived fields appear after inherited fields. If a class declares a virtual method, its first field is the VMT pointer, which appears after all the inherited fields. (Unlike a new-style object, where the VMT pointer is always first because TObject declares virtual methods.) An old-style object type can have private, protected, and public sections, but not published or automated sections. Because it can not have a published section, an old object type can not have any runtime type information. An old object type can not implement interfaces. Constructors and destructors work differently In Old-Style Object Types Than in New-Style Class of An Old Object Type, Call The New Procedure. The Newly Allocated Object IS Initialized to All Zero.

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

New Post(0)