![]() |
Open CASCADE Technology
6.7.1
|
This manual explains how to use Open CASCADE Technology (OCCT) Foundation Classes. It provides basic documentation on foundation classes. For advanced information on foundation classes and their applications, see our offerings on our web site at www.opencascade.org/support/training/ Foundation Classes provide a variety of general-purpose services such as automated dynamic memory management (manipulation of objects by handle), collections, exception handling, genericity by downcasting and plug-in creation. Foundation Classes include the following:
Root classes are the basic data types and classes on which all the other classes are built. They provide:
Strings are classes that handle dynamically sized sequences of characters based on both ASCII (normal 8-bit character type) and Unicode (16-bit character type). Strings may also be manipulated by handles, and consequently be shared. Strings are implemented in the TCollection package.
Collections are the classes that handle dynamically sized aggregates of data. Collection classes are generic, that is, they define a structure and algorithms allowing to hold a variety of objects which do not necessarily inherit from a unique root class (similarly to C++ templates). When you need to use a collection of a given type of object, you must instantiate it for this specific type of element. Once this declaration is compiled, all functions available on the generic collection are available on your instantiated class.
Collections include a wide range of generic classes such as run-time sized arrays, lists, stacks, queues, sets and hash maps. Collections are implemented in the TCollection and NCollection packages.
The TColStd package provides frequently used instantiations of generic classes from the TCollection package with objects from the Standard package or strings from the TCollection package.
These classes provide commonly used mathematical algorithms and basic calculations (addition, multiplication, transposition, inversion, etc.) involving vectors and matrices.
Open CASCADE Technology primitive geometric types are a STEP-compliant implementation of basic geometric and algebraic entities. They provide:
Open CASCADE Technology common math algorithms provide a C++ implementation of the most frequently used mathematical algorithms. These include:
A hierarchy of commonly used exception classes is provided, all based on class Failure, the root of exceptions. Exceptions describe exceptional situations, which can arise during the execution of a function. With the raising of an exception, the normal course of program execution is abandoned. The execution of actions in response to this situation is called the treatment of the exception.
These are various classes supporting date and time information and fundamental types representing most physical quantities such as length, area, volume, mass, density, weight, temperature, pressure etc.
Foundation Classes also include implementation of several low-level services that facilitate the creation of customizable and user-friendly applications with Open CASCADE Technology. These include:
An object-oriented language structures a system around data types rather than around the actions carried out on this data. In this context, an object is an instance of a data type and its definition determines how it can be used. Each data type is implemented by one or more classes, which make up the basic elements of the system.
In Open CASCADE Technology the classes are usually defined using CDL (CASCADE Definition Language) that provides a certain level of abstraction from pure C++ constructs and ensures a definite level of similarity in the implementation of classes. See CDL User’s Guide for more details.
This chapter introduces some basic concepts most of which are directly supported by CDL and used not only in Foundation Classes, but throughout the whole OCCT library.
The whole OCCT library is organized in a set of modules. The first module, providing most basic services and used by all other modules, is called Foundation Classes and described by this manual.
Every module consists primarily of one or several toolkits (though it can also contain executables, resource units etc.). Physically a toolkit is represented by a shared library (e.g. .so or .dll). The toolkit is built from one or several packages.
A package groups together a number of classes which have semantic links. For example, a geometry package would contain Point, Line, and Circle classes. A package can also contain enumerations, exceptions and package methods (functions). In practice, a class name is prefixed with the name of its package e.g. Geom_Circle. Data types described in a package may include one or more of the following data types:
The fundamental software component in object-oriented software development is the class. A class is the implementation of a data type. It defines its behavior (the services offered by its functions) and its representation (the data structure of the class – the fields, which store its data).
Classes fall into three categories:
Generic classes are implemented in two steps. First you declare the generic class to establish the model, then you instantiate this class by giving information about the generic types.
The generic classes in Open CASCADE Technology are similar by their intent to C++ templates with explicit instantiation. A generic class is declared in CDL as operating on data items of non-fixed types which are declared as arguments of the generic class. It is possible to put a restriction on these data types to be of subtype of some definite class. Definition of the generic class does not create new class type in C++ terms; it only defines a pattern for generation (instantiation) of the real classes.
When a generic class is instantiated, its argument types are substituted by actually existing data types (elementary types or classes). The result of instantiation is a new C++ class with an arbitrary name (specified in the instantiating declaration). By convention, the name of the instantiated class is usually constructed from the name of the generic class and names of actual argument types. As for any other class, the name of the class instantiating a generic type is prefixed by the name of the package in which instantiation is declared.
This declaration located in a CDL file of the TColStd package defines a new C++ class TColStd_Array1OfReal as the instantiation of generic class TCollection_Array1 for Real values. More than one class can be instantiated from the same generic class with the same argument types. Such classes will be identical by implementation, but considered as two different classes by C++. No class can inherit from a generic class. A generic class can be a deferred class. A generic class can also accept a deferred class as its argument. In both these cases, any class instantiated from it will also be deferred. The resulting class can then be inherited by another class.
It often happens that many classes are linked by a common generic type. This is the case when a base structure furnishes an iterator. In this context, it is necessary to make sure that the group of linked generic classes is indeed instantiated for the same type of object. In order to group the instantiation, you may declare certain classes as being nested. When generic class is instantiated, its nested classes are instantiated as well. The name of the instantiation of the nested class is constructed from the name of that nested class and name of the main generic class, connected by ‘Of’.
This declaration in TColStd defines not only class TColStd_MapOfReal, but also class TColStd_MapIteratorOfMapOfReal, which is instantiated from nested class MapIterator of the generic class TCollection_Map. Note that instantiation of the nested class is separate class, it is not nested class to the instantiation of the main class. Nested classes, even though they are described as non-generic classes, are generic by construction being inside the class they are a member of.
The purpose of inheritance is to reduce the development workload. The inheritance mechanism allows a new class to be declared already containing the characteristics of an existing class. This new class can then be rapidly specialized for the task in hand. This avoids the necessity of developing each component “from scratch”. For example, having already developed a class BankAccount you could quickly specialize new classes: SavingsAccount, LongTermDepositAccount, MoneyMarketAccount, RevolvingCreditAccount, etc....
The corollary of this is that when two or more classes inherit from a parent (or ancestor) class, all these classes guarantee as a minimum the behavior of their parent (or ancestor). For example, if the parent class BankAccount contains the method Print which tells it to print itself out, then all its descendent classes guarantee to offer the same service.
One way of ensuring the use of inheritance is to declare classes at the top of a hierarchy as being deferred. In such classes, the methods are not implemented. This forces the user to create a new class which redefines the methods. This is a way of guaranteeing a certain minimum of behavior among descendent classes.
The data types in Open CASCADE Technology fall into two categories:
A variable of a type manipulated by handle which is not attached to an object is said to be null. To reference an object, we instantiate the class with one of its constructors. For example, in C++:
In Open CASCADE Technology, the Handles are specific classes that are used to safely manipulate objects allocated in the dynamic memory by reference, providing reference counting mechanism and automatic destruction of the object when it is not referenced.
The behavior of any object is implemented by the methods, which were defined in its class declaration. The definition of these methods includes not only their signature (their programming interface) but also their domain of validity.
This domain is expressed by exceptions. Exceptions are raised under various error conditions. This mechanism is a safeguard of software quality.
The data schema is the structure used by an application to store its data. Data schemas consist of persistent classes.
An object is called persistent if it can be permanently stored. Thus, the object can be reused at a later date by the application, which created it, or by another application.
In order for an object to be persistent for CDL, its type must be declared as inheriting from the class Standard_Persistent or have a parent class inheriting from the Standard_Persistent class. Note that classes inheriting from Standard_Persistent are handled by a reference.
Objects instantiated from classes which inherit from the Standard_Storable class cannot themselves be stored individually, but they can be stored as fields of an object which inherits from Standard_Persistent. Note that objects inheriting from Standard_Storable are handled by a value.
This chapter deals with basic services such as memory management, programming with handles, primitive types, exception handling, genericity by downcasting and plug-in creation.
The primitive types are predefined in the language and they are manipulated by value. Some of these primitives inherit from the Storable class. This means they can be used in the implementation of persistent objects, either contained in entities declared within the methods of the object, or they form part of the internal representation of the object.
The primitives inheriting from Standard_Storable are the following:
Table 1: Equivalence between C++ Types and OCCT Primitive Types
C++ Types | OCCT Types |
---|---|
int | Standard_Integer |
double | Standard_Real |
float | Standard_ShortReal |
unsigned int | Standard_Boolean |
char | Standard_Character |
short | Standard_ExtCharacter |
char* | Standard_CString |
void* | Standard_Address |
short* | Standard_ExtString |
Reminder of the classes listed above:
There are three categories of types which are manipulated by value:
There are two categories of types which are manipulated by handle:
The following table summarizes how various data types are handled and stored.
Type | Manipulated by handle | Manipulated by value |
---|---|---|
storable | Persistent | Primitive, Storable (if nested in a persistent class) |
temporary | Transient | Other |
A handle may be compared with a C++ pointer. Several handles can reference the same object. Also, a single handle may reference several objects, but only one at a time. To have access to the object it refers to, the handle must be de-referenced just as with a C++ pointer.
Transient and Persistent classes may be manipulated either with handles or with values. Handles which reference non-persistent objects are called non-storable handles; therefore, a persistent object cannot contain a non-storable handle.
Classes used with handles are persistent or transient.
Classes that inherit from Standard_Transient are transient while classes that inherit from Standard_Persistent are persistent.
In this chapter we will discuss only transient classes and relevant handles. Persistent classes and their handles are organized in a similar manner.
Class Standard_Transient is a root of a big hierarchy of OCCT classes that are said to be operable by handles. It provides a reference counter field, inherited by all its descendant classes, that is used by associated Handle() classes to track a number of handles pointing to this instance of the object.
For every class derived (directly or indirectly) from Transient, CDL extractor creates associated class Handle() whose name is the same as the name of that class prefixed by Handle_. Open CASCADE Technology provides preprocessor macro Handle() that produces a name of a Handle() class for a given transient class name.
A handle is characterized by the object it references.
Before performing any operation on a transient object, you must declare the handle. For example, if Point and Line are two transient classes from the Geom package, you would write:
Declaring a handle creates a null handle that does not refer to any object. The handle may be checked to be null by its method IsNull(). To nullify a handle, use method Nullify().
To initialize a handle, either a new object should be created or the value of another handle can be assigned to it, on condition that their types are compatible.
Note that handles should only be used for object sharing. For all local operations, it is advisable to use classes manipulated by values.
Open CASCADE Technology provides a means to describe the hierarchy of data types in a generic way, with a possibility to check the exact type of the given object at run-time (similarly to C++ RTTI). For every class type derived from Standard_Transient, CDL extractor creates a code instantiating single instance of the class Standard_Type (type descriptor) that holds information on that type: its name and list of ancestor types. That instance (actually, a handle on it) is returned by the virtual method DynamicType() of the class derived from Standard_Transient. The other virtual method IsKind() provides a means to check whether a given object has specified type or inherits it.
In order to refer to the type descriptor object for a given class type, use macros STANDARD_TYPE() with argument being a name of the class.
The type used in the declaration of a handle is the static type of the object, the type seen by the compiler. A handle can reference an object instantiated from a subclass of its static type. Thus, the dynamic type of an object (also called the actual type of an object) can be a descendant of the type which appears in the handle declaration through which it is manipulated.
Consider the persistent class CartesianPoint, a sub-class of Point; the rule of type conformity can be illustrated as follows:
The compiler sees p1 as a handle to Point though the actual object referenced by p1 is of the CartesianPoint type.
According to the rule of type conformity, it is always possible to go up the class hierarchy through successive assignments of handles. On the other hand, assignment does not authorize you to go down the hierarchy. Consequently, an explicit type conversion of handles is required.
A handle can be converted explicitly into one of its sub-types if the actual type of the referenced object is a descendant of the object used to cast the handle. If this is not the case, the handle is nullified (explicit type conversion is sometimes called a “safe cast”). Consider the example below.
If conversion is not compatible with the actual type of the referenced object, the handle which was “cast” becomes null (and no exception is raised). So, if you require reliable services defined in a sub-class of the type seen by the handle (static type), write as follows:
Downcasting is used particularly with collections of objects of different types; however, these objects should inherit from the same root class.
For example, with a sequence of transient objects SequenceOfTransient and two classes A and B that both inherit from Standard_Transient, you get the following syntax:
To create an object which is manipulated by handle, declare the handle and initialize it with the standard C++ new operator, immediately followed by a call to the constructor. The constructor can be any of those specified in the source of the class from which the object is instanced.
Unlike for a pointer, the delete operator does not work on a handle; the referenced object is automatically destroyed when no longer in use.
Once you have a handle on a persistent or transient object, you can use it like a pointer in C++. To invoke a method which acts on the referenced object, you translate this method by the standard arrow operator, or alternatively, by function call syntax when this is available.
To test or to modify the state of the handle, the method is translated by the dot operator. The example below illustrates how to access the coordinates of an (optionally initialized) point object:
The example below illustrates how to access the type object of a Cartesian point:
NullObject exception will be raised if a field or a method of an object is accessed via a Null handle.
A class method is called like a static C++ function, i.e. it is called by the name of the class of which it is a member, followed by the “::” operator and the name of the method.
For example, we can find the maximum degree of a Bezier curve:
Before you delete an object, you must ensure it is no longer referenced. To reduce the programming load related to this management of object life, the delete function in Open CASCADE Technology is secured by a reference counter of classes manipulated by handle. A handle automatically deletes an object when it is no longer referenced. Normally you never call the delete operator explicitly on instances of subclasses of Standard_Transient.
When a new handle to the same object is created, the reference counter is incremented. When the handle is destroyed, nullified, or reassigned to another object, that counter is decremented. The object is automatically deleted by the handle when reference counter becomes 0.
The principle of allocation can be seen in the example below.
Cycles appear if two or more objects reference each other by handles (stored as fields). In this condition automatic destruction will not work.
Consider for example a graph, whose objects (primitives) have to know the graph object to which they belong, i.e. a primitive must have a reference to complete graph object. If both primitives and the graph are manipulated by handle and they refer to each other by keeping a handle as a field, the cycle appears. The graph object will not be deleted when the last handle to it is destructed in the application, since there are handles to it stored inside its own data structure (primitives).
There are two approaches how to avoid such situation:
Though generation of Handle class and related C++ code is normally performed by CDL extractor, it is also possible to define a class managed by handle without CDL. To facilitate that, several macros are provided in the file Standard_DefineHandle.hxx:
In Appli_ExtSurface.hxx file:
In Appli_ExtSurface.cxx file:
In the course of a work session, geometric modeling applications create and delete a considerable number of C++ objects allocated in the dynamic memory (heap). In this context, performance of standard functions for allocating and deallocating memory may be not sufficient. For this reason, Open CASCADE Technology employs a specialized memory manager implemented in the Standard package.
To use the Open CASCADE Technology memory manager to allocate memory in a C code, just use method Standard::Allocate() instead of malloc() and method Standard::Free() instead of free(). In addition, method Standard::Reallocate() is provided to replace C function realloc().
In C++, operators new() and delete() for a class may be defined so as to allocate memory using Standard::Allocate() and free it using Standard::Free(). In that case all objects of that class and all inherited classes will be allocated using the OCCT memory manager.
CDL extractor defines new() and delete() in this way for all classes declared with CDL. Thus all OCCT classes (apart from a few exceptions) are allocated using the OCCT memory manager. Since operators new() and delete() are inherited, this is also true for any class derived from an OCCT class, for instance, for all classes derived from Standard_Transient.
Note that it is possible (though not recommended unless really unavoidable) to redefine new() and delete() functions for some class inheriting Standard_Transient. If that is done, the method Delete() should be also redefined to apply operator delete to this pointer. This will ensure that appropriate delete() function will be called, even if the object is manipulated by a handle to a base class.
The OCCT memory manager may be configured to apply different optimization techniques to different memory blocks (depending on their size), or even to avoid any optimization and use C functions malloc() and free() directly. The configuration is defined by numeric values of the following environment variables:
Note it is recommended to use options MMGT_OPT=2 and MMGT_REENTRANT=1 for applications that use OCCT memory manager from more than one thread, on multiprocessor hardware.
When MMGT_OPT is set to 1, the following optimization techniques are used:
In the current version memory pools are never returned to the system (until the process finishes). However, memory blocks that are released by the method Standard::Free() are remembered in the free lists and later reused when the next block of the same size is allocated (recycling).
However, unlike small blocks, the recycled medium blocks contained in the free lists (i.e. released by the program but held by the memory manager) can be returned to the heap by method Standard::Purge().
The major benefit of the OCCT memory manager is explained by its recycling of small and medium blocks that makes an application work much faster when it constantly allocates and frees multiple memory blocks of similar sizes. In practical situations, the real gain on the application performance may be up to 50%.
The associated drawback is that recycled memory is not returned to the operating system during program execution. This may lead to considerable memory consumption and even be misinterpreted as a memory leak. To minimize this effect, the method Standard::Purge() shall be called after the completion of memory-intensive operations. The overhead expenses induced by the OCCT memory manager are:
Note that these overheads may be greater or less than overheads induced by the C heap memory manager, so overall memory consumption may be greater in either optimized or standard modes, depending on circumstances.
As a general rule, it is advisable to allocate memory through significant blocks. In this way, you can work with blocks of contiguous data, and processing is facilitated for the memory page manager.
In multithreaded mode (MMGT_REENTRANT=1), the OCCT memory manager uses mutex to lock access to free lists, therefore it may have less performance than non-optimized mode in situations when different threads often make simultaneous calls to the memory manager. The reason is that modern implementations of malloc() and free() employ several allocation arenas and thus avoid delays waiting mutex release, which are possible in such situations.
Exception handling provides a means of transferring control from a given point in a program being executed to an exception handler associated with another point previously executed.
A method may raise an exception which interrupts its normal execution and transfers control to the handler catching this exception.
Open CASCADE Technology provides a hierarchy of exception classes with a root class being class Standard_Failure from the Standard package. The CDL extractor generates exception classes with standardized interface.
Open CASCADE Technology also provides support for converting system signals (such as access violation or division by zero) to exceptions, so that such situations can be safely handled with the same uniform approach.
However, in order to support this functionality on various platforms, some special methods and workarounds are used. Though the implementation details are hidden and handling of OCCT exceptions is done basically in the same way as with C++, some peculiarities of this approach shall be taken into account and some rules must be respected.
The following paragraphs describe recommended approaches for using exceptions when working with Open CASCADE Technology.
To raise an exception of a definite type method Raise() of the appropriate exception class shall be used.
raises an exception of DomainError type with the associated message “Cannot cope with this condition”, the message being optional. This exception may be caught by a handler of a DomainError type as follows:
Exceptions should not be used as a programming technique, to replace a “goto” statement for example, but as a way to protect methods against misuse. The caller must make sure its condition is such that the method can cope with it.
Thus,
For example, if you consider the TCollection_Array1 class used with:
then, the Value function may be implemented as follows:
Here validity of the index is first verified using the Lower and Upper functions in order to protect the call. Normally the caller ensures the index being in the valid range before calling Value(). In this case the above implementation of Value is not optimal since the test done in Value is time-consuming and redundant.
It is a widely used practice to include that kind of protections in a debug build of the program and exclude in release (optimized) build. To support this practice, the macros Raise_if() are provided for every OCCT exception class:
where ErrorTypeName is the exception type, condition is the logical expression leading to the raise of the exception, and Error message is the associated message.
The entire call may be removed by defining one of the pre-processor symbols No_Exception or No_<ErrorTypeName> at compile-time:
Using this syntax, the Value function becomes:
When an exception is raised, control is transferred to the nearest handler of a given type in the call stack, that is:
A handler of T exception type is a match for a raise expression with an exception type of E if:
In order to handle system signals as exceptions, make sure to insert macro OCC_CATCH_SIGNALS somewhere in the beginning of the relevant code. The recommended location for it is first statement after opening brace of try {} block.
As an example, consider the exceptions of type NumericError, Overflow, Underflow and ZeroDivide, where NumericError is the parent type of the three others.
Here, the first handler will catch exceptions of Overflow type and the second one - exceptions of NumericError type and all exceptions derived from it, including Underflow and ZeroDivide.
The handlers are checked in order of appearance, from the nearest to the most distant try block, until one matches the raise expression. For a try block, it would be a mistake to place a handler for a base exception type ahead of a handler for its derived type since that would ensure that the handler for the derived exception would never be invoked.
The exceptions form a hierarchy tree completely separated from other user defined classes. One exception of type Failure is the root of the entire exception hierarchy. Thus, using a handler with Failure type catches any OCCT exception. It is recommended to set up such a handler in the main routine.
The main routine of a program would look like this:
In this example function Caught is a static member of Failure that returns an exception object containing the error message built in the raise expression. Note that this method of accessing a raised object is used in Open CASCADE Technology instead of usual C++ syntax (receiving the exception in catch argument).
Though standard C++ scoping rules and syntax apply to try block and handlers, note that on some platforms Open CASCADE Technology may be compiled in compatibility mode when exceptions are emulated by long jumps (see below). In this mode it is required that no statement precedes or follows any handler. Thus it is highly recommended to always include a try block into additional {} braces. Also this mode requires that header file Standard_ErrorHandler.hxx be included in your program before a try block, otherwise it may fail to handle Open CASCADE Technology exceptions; furthermore catch() statement does not allow passing exception object as argument.
In order for the application to be able to catch system signals (access violation, division by zero, etc.) in the same way as other exceptions, the appropriate signal handler shall be installed in the runtime by the method OSD::SetSignal().
Normally this method is called in the beginning of the main() function. It installs a handler that will convert system signals into OCCT exceptions.
In order to actually convert signals to exceptions, macro OCC_CATCH_SIGNALS needs to be inserted in the source code. The typical place where this macro is put is beginning of the try{} block which catches such exceptions.
The exception handling mechanism in Open CASCADE Technology is implemented in different ways depending on the preprocessor macros NO_CXX_EXCEPTIONS and OCC_CONVERT_SIGNALS, which shall be consistently defined by compilation procedures for both Open CASCADE Technology and user applications:
On SUN and Linux, macro OCC_CONVERT_SIGNALS is defined by default. The C++ exception mechanism is used for catching exceptions and for throwing them from normal code. Since it is not possible to throw C++ exception from system signal handler function, that function makes a long jump to the nearest (in the execution stack) invocation of macro OCC_CATCH_SIGNALS, and only there the C++ exception gets actually thrown. The macro OCC_CATCH_SIGNALS is defined in the file Standard_ErrorHandler.hxx. Therefore, including this file is necessary for successful compilation of a code containing this macro.
This mode differs from standard C++ exception handling only for signals:
While exception handling with NO_CXX_EXCEPTIONS is very similar to C++ by syntax, it has a number of peculiarities that should be taken into account: