c builder

Problem:

Getting the error "Access Violation at address XXXXXX in module coreide60.bpl" when start up Delphi or C++Builder.

Solution:

The exact cause for this is not currently known. It seems to happen sometimes with a new installation of Delphi on Windows XP.
Possible solutions:

   Reset the user registry settings by running the utility D6RegClean.exe which is located in the Delphi bin directory.

   Reinstall Delphi, running the utility above after uninstalling (it is also located on the CD).

   It is possible that the problem is linked to setting options in Delphi, such as the desktop preferences, before first running a project for the first time.

It is important to note that the registry settings for each user are set the first time Delphi is run, so be sure to run Delphi once after installing, before installing any 3rd party components.

 

Although the various list classes contain different types of items and have different ancestries, most of them share a common set of methods for adding, deleting, rearranging, and accessing the items in the list.

Adding list items

Most list classes have an Add method, which lets you add an item to the end of the list (if it is not sorted) or to its appropriate position (if the list is sorted). Typically, the Add method takes as a parameter the item you are adding to the list and returns the position in the list where the item was added. In the case of bucket lists (TBucketList and TObjectBucketList), Add takes not only the item to add, but also a datum you can associate with that item. In the case of collections, Add takes no parameters, but creates a new item that it adds. The Add method on collections returns the item it added, so that you can assign values to the new item's properties.

Some list classes have an Insert method in addition to the Add method. Insert works the same way as the Add method, but has an additional parameter that lets you specify the position in the list where you want the new item to appear. If a class has an Add method, it also has an Insert method unless the position of items is predetermined For example, you can't use Insert with sorted lists because items must go in sort order, and you can't use Insert with bucket lists because the hash algorithm determines the item position.

The only classes that do not have an Add method are the ordered lists. Ordered lists are queues and stacks. To add items to an ordered list, use the Push method instead. Push, like Add, takes an item as a parameter and inserts it in the correct position.

Deleting list items

To delete a single item from one of the list classes, use either the Delete method or the Remove method. Delete takes a single parameter, the index of the item to remove. Remove also takes a single parameter, but that parameter is a reference to the item to remove, rather than its index. Some list classes support only a Delete method, some support only a Remove method, and some have both.

As with adding items, ordered lists behave differently than all other lists. Instead of using a Delete or Remove method, you remove an item from an ordered list by calling its Pop method. Pop takes no arguments, because there is only one item that can be removed.

If you want to delete all of the items in the list, you can call the Clear method. Clear is available for all lists except ordered lists.

Accessing list items

All list classes (except TThreadList and the ordered lists) have a property that lets you access the items in the list. Typically, this property is called Items. For string lists, the property is called Strings, and for bucket lists it is called Data. The Items, Strings, or Data property is an indexed property, so that you can specify which item you want to access.

On TThreadList, you must lock the list before you can access items. When you lock the list, the LockList method returns a TList object that you can use to access the items.

Ordered lists only let you access the "top" item of the list. You can obtain a reference to this item by calling the Peek method.

Rearranging list items

Some list classes have methods that let you rearrange the items in the list. Some have an Exchange method, that swaps the position of two items. Some have a Move method that lets you move an item to a specified location. Some have a Sort method that lets you sort the items in the list.
To see what methods are available, check the Online help for the list class you are using.

Persistent Lists

Persistent lists can be saved to a form file. Because of this, they are often used as the type of a published property on a component. You can add items to the list at design time, and those items are saved with the object so that they are there when the component that uses them is loaded into memory at runtime. There are two main types of persistent lists: string lists and collections.

Examples of string lists include TStringList and THashedStringList. String lists, as the name implies, contain strings. They provide special support for strings of the form Name=Value, so that you can look up the value associated with a name. In addition, most string lists let you associate an object with each string in the list. String lists are described in more detail in Working with string lists.

Collections descend from the class TCollection. Each TCollection descendant is specialized to manage a specific class of items, where that class descends from TCollectionItem. Collections support many of the common list operations. All collections are designed to be the type of a published property, and many can not function independently of the object that uses them to implement on of its properties.

At design time, the property whose value is a collection can use the collection editor to let you add, remove, and rearrange items. The collection editor provides a common user interface for manipulating collections.

 

This article give you descriptions to the TCollection, TStringList and THashedStringList in Delphi / C++Builder. These base vcl/clx component are very useful in programming.

TCollection

TCollection is a container for TCollectionItem objects.

TCollection is in Unit Classes.

Description

Each TCollection holds a group of TCollectionItem descendants. TCollection maintains an index of the collection items in its Items array. The Count property contains the number of items in the collection. Use the Add and Delete methods to add items to the collection and delete items from the collection.

Objects descended from TCollection can contain objects descended from TCollectionItem. Thus, for each TCollection descendant, there is a corresponding TCollectionItem descendant. The following table lists some typical descendants of TCollection with the corresponding TCollectionItem descendant and the component that uses each pair.

TCollection descendant
TCollectionItem descendant
Component
TAggregates TAggregate TClientDataSet
TCookieCollection TCookie TWebResponse
TDBGridColumns TColumn TDBGrid
TFieldDefs TFieldDef TDataSet
THeaderSections THeaderSection THeaderControl
TListColumns TListColumn TListView
TParams TParam many datasets
TStatusPanels TStatusPanel TStatusBar

The controls that use TCollection and TCollectionItem descendants have a published property that holds a collection. (For example, the Panels property of TStatusBar holds a TStatusPanels.) A standard property editor, referred to generically as the Collection editor, can be invoked from the Object Inspector to edit the items in the collection.

Note: When writing a TCollection descendant that is used by another control, be sure to override the protected GetOwner method of the collection so that it can appear in the Object Inspector.

TStringList

TStringList maintains a list of strings.

TStringList is in Unit Classes.

Description

Use a string list object to store and manipulate a list of strings. TStringList implements the abstract properties and methods introduced by TStrings, and introduces new properties, events, and methods to

Sort the strings in the list.
Prohibit duplicate strings in sorted lists.
Respond to changes in the contents of the list.
Control whether strings are located, sorted, and identified as duplicates in a case-sensitive or case-insensitive manner.

THashedStringList

THashedStringList maintains a list of strings using an internal hash table.

THashedStringList is in Unit IniFiles.

Description

THashedStringList is a string list that uses a hash table internally to speed the process of locating strings. It is used internally by TMemIniFile to manage the strings from an INI file, but can be used in the same way as any other string list. By using THashedStringList instead of TStringList, you can improve performance when the list contains a large number of strings.

 

TObjectBucketList

TObjectBucketList is a simple hash table that stores objects that are identified by other objects.

TObjectBucketList is in Unit Contnrs.

Description

Use TObjectBucketList as a simple hash table to store objects that are indexed by other objects. TObjectBucketList includes methods to add, remove, and locate items in the list, as well as a method that executes a callback for every item in the list.

 

TObjectList

TObjectList maintains a list of (owned) objects.

TObjectList is in Unit Contnrs.

Description

Use TObjectList to store and maintain a list of objects. TObjectList provides properties and methods to add, delete, rearrange, locate, access, and sort objects. If the OwnsObjects property is set to true (the default), TObjectList controls the memory of its objects, freeing an object when its index is reassigned; when it is removed from the list with the Delete, Remove, or Clear method; or when the TObjectList instance is itself destroyed.

 

TComponentList

TComponentList maintains a list of components, updating itself when a component is freed.

TComponentList is in Unit Contnrs.

Description

Use TComponentList to store and maintain a list of components. TComponentList provides properties and methods to add, delete, rearrange, locate, access, and sort components. Like TObjectList, TComponentList controls the memory of its components; unless the OwnsObjects property is set to false (or the components are removed with the Extract method). TComponentList frees its components when they are removed from the list or when the TComponentList instance is itself destroyed.

In addition, TComponentList tracks its components. When a component is freed, TComponentList automatically updates itself by deleting the reference to the freed component and packing the list.

 

TClassList

TClassList maintains a list of classes.

TClassList is in Unit Contnrs.

Description

Use a TClassList object to store and maintain a list of classes.

 

TInterfaceList

TInterfaceList represents a list of interfaces.

TInterfaceList is in Unit Classes.

Description

Use TInterfaceList to manage a list of interfaces.

 

TQueue

TQueue maintains a first-in first-out array of pointers.

TQueue is in Unit Contnrs.

Description

Use a TQueue object to store and maintain a first-in first-out list.

 

TStack

TStack maintains a last-in first-out array of pointers.

TStack is in Unit Contnrs.

Description

Use a TStack object to store and maintain a last-in first-out list.

 

TObjectQueue

TObjectQueue maintains a first-in first-out list of objects.

TObjectQueue is in Unit Contnrs.

Description

Use a TObjectQueue to store and maintain a first-in first-out list of objects.

 

TObjectStack

TObjectStack maintains a last-in first-out list of objects.

TObjectStack is in Unit Contnrs.

Description

Use TObjectStack to store and maintain a last-in first-out list of objects.

 

BaseCLX includes many classes that represents lists or collections of items. They vary depending on the types of items they contain, what operations they support, and whether they are persistent.

The following table lists various list classes, and indicates the types of items they contain:BaseCLX includes many classes that represents lists or collections of items. They vary depending on the types of items they contain, what operations they support, and whether they are persistent.

The following table lists various list classes, and indicates the types of items they contain:

Object Maintains
TList  A list of pointers
TThreadList  A thread-safe list of pointers
TBucketList  A hashed list of pointers
TObjectBucketList  A hashed list of object instances
TObjectList  A memory-managed list of object instances
TComponentList  A memory-managed list of components (that is, instances of classes descended from TComponent)
TClassList A list of class references (metaclasses)
TInterfaceList A list of interface pointers.
TQueue  A first-in first-out list of pointers
TStack  A last-in first-out list of pointers
TObjectQueue A first-in first-out list of objects
TObjectStack A last-in first-out list of objects
TCollection  Base class for many specialized classes of typed items.
TStringList  A list of strings
THashedStringList A list of strings with the form Name=Value, hashed for performance.

TList Description.

TList is in Classes Unit.

TList, which stores an array of pointers, is often used to maintain lists of objects. TList introduces properties and methods to

Add or delete the objects in the list.
 Rearrange the objects in the list.
 Locate and access objects in the list.
 Sort the objects in the list.

TThreadList Description.

TThreadList is in Classes Unit.

A TThreadList object is a thread-safe list. Each TThreadList maintains a private TList (a list of pointers to objects). You can add or remove items in a TThreadList from multiple threads without explicit locks.

To access the actual TList object managed by the thread list, first lock the list by calling the LockList method.  Unlock the list by calling the Unlock method when done.

Tip: By default, TThreadList ignores attempts to add duplicate entries to the list. If the list is large, this default is computationally expensive. For better performance, you may want to change the Duplicates property to dupAccept where possible.

TBucketList Description.

TBucketList is a simple hash table that stores pointers indexed by pointers.

TBucketList is in Contnrs Unit.

Use TBucketList as a simple hash table to store data pointers using identifiers that can be represented as pointers. TBucketList includes methods to add, remove, and locate items in the list, as well as a method that executes a callback for every item in the list.

 

The base VCL and CLX in Delphi means the base classes which are invisible. Some of these are very important, you will always meet them and use them when you programming in the future.

There are a number of units that are common to both the VCL and CLX that provide the underlying support for both component libraries. Collectively, these units are called BaseCLX. BaseCLX does not include any of the components that appear on the component palette. Rather, it includes a number of classes and global routines that are used by the components that do appear on the component palette. These classes and routines are also available for you to use in application code or when you are writing your own classes.

Note: The global routines that make up BaseCLX are often called the runtime library. Do not confuse these routines with the C++ runtime library. Many of these perform functions similar to those in the C++ runtime library, but can be distinguished because the function names begin with a capital letter and they are declared in the header of a unit.

The following topics discuss many of the classes and routines that make up BaseCLX and illustrate how to use them:

Note: This list of tasks is not exhaustive. The runtime library in BaseCLX contains many routines to perform tasks that are not mentioned here. These include a host of mathematical functions (defined in the Math unit), routines for working with date/time values (defined in the SysUtils and DateUtils units), and routines for working with Object Pascal Variants (defined in the Variants unit).

 

The following diagram is a greatly simplified view of the inheritance hierarchy that illustrates the relationship between objects, components, and controls.

VCL-inheritance-hierarchy.gif
Objects, components, and controls

VCL-inheritance-hierarchy-2.gif

Every object inherits from TObject, and many objects inherit from TComponent. Controls inherit from TControl and have the ability to display themselves at runtime. A control like TCheckBox inherits all the functionality of TObject, TComponent
, and TControl, and adds specialized capabilities of its own.

The following diagram is an overview of the Visual Component Library (VCL) that shows the major branches of the inheritance tree. The Borland Component Library for Cross-Platform (CLX) looks very much the same at this level although TWinControl is replaced by TWidgetControl.

Simplified object hierarchy. 

Class Description
TObject Signifies the base class and ultimate ancestor of everything in the VCL or CLX. TObject encapsulates the fundamental behavior common to all VCL/CLX objects by introducing methods that perform basic functions such as creating, maintaining, and destroying an instance of an object.
Exception Specifies the base class of all classes that relate to exceptions. Exception provides a consistent interface for error conditions, and enables applications to handle error conditions gracefully.
TPersistent Specifies the base class for all objects that implement properties. Classes under TPersistent deal with sending data to streams and allow for the assignment of classes.
TComponent Specifies the base class for all nonvisual components such as TApplication. TComponent is the common ancestor of all components. This class allows a component to be displayed on the Component palette, lets the component own other components, and allows the component to be manipulated directly on a form. 
TControl Represents the base class for all controls that are visible at runtime. TControl is the common ancestor of all visual components and provides standard visual controls like position and cursor. This class also provides events that respond to mouse actions. 
TWinControl Specifies the base class of all user interface objects. Controls under TWinControl are windowed controls that can capture keyboard input. In CLX, these are called widgets, and TWidgetControl replaces 
 

Many 32-bit Windows applications store their information in the system Registry instead of ini files because the Registry is hierarchical and doesn't suffer from the size limitations of ini files. If you are accustomed to using ini files and want to move your configuration information to the Registry instead, you can use the TRegistryIniFile class. You may also want to use TRegistryIniFile in cross-platform applications if you want to use the system Registry on Windows and an ini file on Linux. You can write most of your application so that it uses the TCustomIniFile type. You need only conditionalize the code that creates an instance of TRegistryIniFile (on Windows) or TMemIniFile (on Linux) and assigns it to the TCustomIniFile your application uses.

TRegistryIniFile makes Registry entries look like ini file entries. All the methods from TIniFile and TMemIniFile (read and write) exist in TRegistryIniFile.
When you construct a TRegistryIniFile object, the parameter you pass to the constructor (corresponding to the filename for an IniFile or TMemIniFile object) becomes a key value under the user key in the registry. All sections and values branch from that root. TRegistryIniFile simplifies the Registry interface considerably, so you may want to use it instead of the TRegistry component even if you aren't porting existing code or writing a cross-platform application.

If you are writing a Windows-only application and are comfortable with the structure of the system Registry, you can use TRegistry. Unlike TRegistryIniFile, which uses the same properties and methods of other ini file components, the properties and methods of TRegistry correspond more directly to the structure of the system Registry. For example, TRegistry lets you specify both the root key and subkey, while TRegistry assumes HKEY_CURRENT_USER as a root key. In addition to methods for opening, closing, saving, moving, copying, and deleting keys, TRegistry lets you specify the access level you want to use.

Note: TRegistry is not available for cross-platform programming.

The following example retrieves a value from a registry entry:

#include

AnsiString GetRegistryValue(AnsiString KeyName) {   AnsiString S;   TRegistry *Registry = new TRegistry(KEY_READ);
  try   {
    Registry->RootKey = HKEY_LOCAL_MACHINE;     // False because we do not want to create it if it doesn't exist     Registry->OpenKey(KeyName,false);     S = Registry->ReadString("VALUE1");   }   __finally   {    delete Registry;   }   return S; }

 

Many applications use ini files to store configuration information. BaseCLX includes two classes for working with ini files: TIniFile and TMemIniFile. Using ini files has the advantage that they can be used in cross-platform applications and they are easy to read and edit. For information on these classes, see Using TIniFile and TMemIniFile below for more information.

Many Windows applications replace the use of ini files with the system Registry. The Windows system Registry is a hierarchical database that acts as a centralized storage space for configuration information. The VCL includes classes for working with the system Registry. While these are technically not part of BaseCLX (because they are only available on Windows), two of these classes, TRegistryIniFile and TRegistry, are discussed here because of their similarity to the classes for working with ini files.

Using TIniFile and TMemIniFile

The ini file format is still popular, many configuration files (such as the DSK Desktop settings file) are in this format. This format is especially useful in cross-platform applications, where you can't always count on a system Registry for storing configuration information. BaseCLX provides two classes, TIniFile and TMemIniFile, to make reading and writing ini files very easy.

On Linux, TMemIniFile and TIniFile are identical. On Windows, TIniFile works directly with the ini file on disk while TMemIniFile buffers all changes in memory and does not write them to disk until you call the UpdateFile method.

When you instantiate the TIniFile or TMemIniFile object, you pass the name of the ini file as a parameter to the constructor. If the file does not exist, it is automatically created. You are then free to read values using the various read methods, such as ReadString, ReadDate, ReadInteger, or ReadBool. Alternatively, if you want to read an entire section of the ini file, you can use the ReadSection method. Similarly, you can write values using methods such as WriteBool, WriteInteger, WriteDate, or WriteString.

Following is an example of reading configuration information from an ini file in a form's constructor and writing values in the OnClose event handler.

__fastcall TForm1::TForm1(TComponent *Owner) : TForm(Owner)
{
   TIniFile *ini;
   ini = new TIniFile( ChangeFileExt( Application->ExeName, ".INI" ) );
   Top     =  ini->ReadInteger( "Form", "Top", 118);
   Left    =  ini->ReadInteger( "Form", "Left", 268);
   Caption =  ini->ReadString( "Form", "Caption",
                               "Default Caption" );
   ini->ReadBool( "Form", "InitMax", false ) ?
         WindowState = wsMaximized :
         WindowState = wsNormal;
   delete ini;
}

void __fastcall TForm1::FormClose(TObject *Sender, TCloseAction &Action)
{
   TIniFile *ini;
   ini = new TIniFile(ChangeFileExt( Application->ExeName, ".INI" ) );
   ini->WriteInteger( "Form", "Top", Top );
   ini->WriteInteger( "Form", "Left", Left );
   ini->WriteString ( "Form", "Caption", Caption );
   ini->WriteBool   ( "Form", "InitMax",
                       WindowState == wsMaximized );
   delete ini;
}

Each of the Read routines takes three parameters. The first parameter identifies the section of the ini file. The second parameter identifies the value you want to read, and the third is a default value in case the section or value doesn't exist in the ini file. Just as the Read methods gracefully handle the case when a section or value does not exist, the Write routines create the section and/or value if they do not exist. The example code creates an ini file the first time it is run that looks like this:

[Form]

Top=210
Left=320
Caption=Default Caption
InitMax=0

On subsequent execution of this application, the ini values are read in when the form is created and written back out in the OnClose event.

 

Several common file operations are built into the BaseCLX runtime library. The procedures and functions for working with files operate at a high level. For most routines, you specify the name of the file and the routine makes the necessary calls to the operating system for you. In some cases, you use file handles instead.

Caution: Although the Object Pascal language is not case sensitive, the Linux operating system is. Be attentive to case when working with files in cross-platform applications.

The following topics describe how to use runtime library routines to perform file manipulation tasks:

Delete a File.

Deleting a file erases the file from the disk and removes the entry from the disk's directory. There is no corresponding operation to restore a deleted file, so applications should generally allow users to confirm before deleting files. To delete a file, pass the name of the file to the DeleteFile function:

DeleteFile(FileName);

DeleteFile returns true if it deleted the file and false if it did not (for example, if the file did not exist or if it was read-only). DeleteFile erases the file named by FileName from the disk, for example:

DeleteFile("c:\\my documents\\test.txt");

Finding a File:

There are three routines used for finding a file: FindFirst, FindNext, and FindClose. FindFirst searches for the first instance of a filename with a given set of attributes in a specified directory. FindNext returns the next entry matching the name and attributes specified in a previous call to FindFirst. FindClose releases memory allocated by FindFirst. You should always use FindClose to terminate a FindFirst/FindNext sequence. If you want to know if a file exists, a FileExists function returns true if the file exists, false otherwise.

The three file find routines take a TSearchRec as one of the parameters. TSearchRec defines the file information searched for by FindFirst or FindNext. The declaration for TSearchRec is:

struct TSearchRec
{ int Time; // time stamp of the file int Size; // size of the file in bytes int Attr; // file attribute flags AnsiString Name; // filename and extension int ExcludeAttr; // file attribute flags for files to ignore unsigned FindHandle; _WIN32_FIND_DATAA FindData; // structure with addition information } ;

If a file is found, the fields of the TSearchRec type parameter are modified to describe the found file. You can test Attr against the following attribute constants or values to determine if a file has a specific attribute:

Constant Value Description
faReadOnly 0x00000001 Read-only files
faHidden 0x00000002 Hidden files
faSysFile 0x00000004 System files
faVolumeID 0x00000008 Volume ID files
faDirectory 0x00000010 Directory files
faArchive 0x00000020 Archive files
faAnyFile 0x0000003F Any file

To test for an attribute, combine the value of the Attr field with the attribute constant using the & operator. If the file has that attribute, the result will be greater than 0. For example, if the found file is a hidden file, the following expression will evaluate to true: (SearchRec.Attr & faHidden > 0). Attributes can be combined by OR抜ng their constants or values. For example, to search for read-only and hidden files in addition to normal files, pass (faReadOnly | faHidden) as the Attr parameter.

Example: This example uses a label, a button named Search, and a button named Again on a form. When the user clicks the Search button, the first file in the specified path is found, and the name and the number of bytes in the file appear in the label's caption. Each time the user clicks the Again button, the next matching filename and size is displayed in the label:

TSearchRec SearchRec; // global variable
void __fastcallTForm1::SearchClick(TObject *Sender)
{
FindFirst("c:\\Program Files\\bcb6\\bin\\*.*", faAnyFile, SearchRec);
Label1->Caption = SearchRec->Name + " is " + IntToStr(SearchRec.Size) + " bytes in size";
}

void __fastcallTForm1::AgainClick(TObject *Sender)
{
if (FindNext(SearchRec) == 0)
Label1->Caption = SearchRec->Name + " is " + IntToStr(SearchRec.Size) + " bytes in size";
else
FindClose(SearchRec);
}

Note: In cross-platform applications, you should replace any hard-coded pathnames with the correct pathname for the system or use environment variables (on the Environment Variables page when you choose Tools|Environment Options) to represent them.

Rename a File.

To change a file name, use the RenameFile function:

extern PACKAGE bool __fastcall RenameFile(const AnsiString OldName, const AnsiString NewName);

RenameFile changes a file name, identified by OldFileName, to the name specified by NewFileName. If the operation succeeds, RenameFile returns true. If it cannot rename the file (for example, if a file called NewFileName already exists), RenameFile returns false. For example:

if (!RenameFile("OLDNAME.TXT","NEWNAME.TXT"))

ErrorMsg("Error renaming file!");

You cannot rename (move) a file across drives using RenameFile. You would need to first copy the file and then delete the old one.

Note: RenameFile in the BaseCLX runtime library is a wrapper around the Windows API MoveFile function, so MoveFile will not work across drives either.

Copy a File.

The BaseCLX runtime library does not provide any routines for copying a file. However, if you are writing Windows-only applications, you can directly call the Windows API CopyFile function to copy a file. Like most of the runtime library file routines, CopyFile takes a filename as a parameter, not a file handle. When copying a file, be aware that the file attributes for the existing file are copied to the new file, but the security attributes are not. CopyFile is also useful when moving files across drives because neither the RenameFile function nor the Windows API MoveFile function can rename or move files across drives.

File Date-Time Routines.

The FileAge, FileGetDate, and FileSetDate routines operate on operating system date-time values. FileAge returns the date-and-time stamp of a file, or -1 if the file does not exist. FileSetDate sets the date-and-time stamp for a specified file, and returns zero on success or an error code on failure. FileGetDate returns a date-and-time stamp for the specified file or -1 if the handle is invalid.
As with most of the file manipulating routines, FileAge uses a string filename. FileGetDate and FileSetDate, however, use an integer parameter which takes a file handle. To get the file handle either

Use the FileOpen or FileCreate function to create a new file or open an existing file. Both FileOpen and FileCreate return the file handle.
Instantiate TFileStream to create or open a file. Then use its Handle property. See Using file streams for more information.

 
Start
Prev
1