Symbian OS Explained - Effective C++ Programming For Smartphones (2005) (779885), страница 25
Текст из файла (страница 25)
As an example, consider an insertion into a flatDYNAMIC BUFFERS107buffer. This may potentially cause it to be reallocated, thus invalidatingany pointers to data in the original heap cell. Likewise, deletion of bufferdata causes data after the deletion point to move up the buffer. For thisreason, it is sensible to reference data in the dynamic buffers only in termsof the buffer position.Let’s take a look at some example code for the dynamic buffers whichstores 8-bit data received from a source of random data. The details ofthe example are not that important; in fact it’s somewhat contrived, andits main purpose is to illustrate the use of the InsertL(), Delete(),Compress(), ExpandL(), Read(), and Write() functions.// Returns random data in an 8-bit heap descriptor of length = aLengthHBufC8* GetRandomDataLC(TInt aLength); // Defined elsewherevoid PrintBufferL(CBufBase* aBuffer){aBuffer->Compress();// Compress to free unused memory at the end of a segmentTInt length = aBuffer->Size();HBufC8* readBuf = HBufC8::NewL(length);TPtr8 writable(readBuf->Des());aBuffer->Read(0, writable);...
// Omitted. Print to the consoledelete readBuf;}void TestBuffersL(){__UHEAP_MARK; // Heap checking macro to test for memory leaksCBufBase* buffer = CBufSeg::NewL(16); // Granularity = 16CleanupStack::PushL(buffer);// There is no NewLC() functionHBufC8* data = GetRandomDataLC(32);// Data is on the cleanup stackbuffer->InsertL(0, *data);// Destroy original. A copy is now stored in the bufferCleanupStack::PopAndDestroy(data);PrintBufferL(buffer);buffer->ExpandL(0, 100); // Pre-expand the bufferTInt pos = 0;for (TInt index = 0; index <4; index++, pos+16){// Write the data in several chunksdata = GetRandomDataLC(16);buffer->Write(pos, *data);CleanupStack::PopAndDestroy(data); // Copied so destroy here}PrintBufferL(buffer);CleanupStack::PopAndDestroy(buffer);__UHEAP_MARKEND;}// Clean up the buffer// End of heap checking108DYNAMIC ARRAYS AND BUFFERSThe dynamic buffer, of type CBufSeg, is instantiated at the beginningof the TestBuffersL() function by a call to CBufSeg::NewL().
A32-byte block of random data is retrieved from GetRandomDataLC()and inserted into the buffer at position 0, using InsertL().The example also illustrates how to pre-expand the buffer usingExpandL() to allocate extra space in the buffer at the position specified(alternatively, you can use ResizeL(), which adds extra memory at theend). These methods are useful if you know there will be a number ofinsertions into the buffer and you wish to make them atomic.
ExpandL()and ResizeL() perform a single allocation, which may fail, but if thebuffer is expanded successfully then data can be added to the array usingWrite(), which cannot fail. This is useful to improve performance, sincemaking a single call which may leave (and thus may need to be called ina TRAP) is far more efficient than making a number of InsertL() calls,each of which needs a TRAP.2 Following the buffer expansion, randomdata is retrieved and written to the buffer in a series of short blocks.The PrintBufferL() function illustrates the use of the Compress(), Size() and Read() methods on the dynamic buffers.
TheCompress() method compresses the buffer to occupy minimal space,freeing any unused memory at the end of a segment for a CBufSeg, orthe end of the flat contiguous buffer for CBufFlat. It’s a useful methodfor freeing up space when memory is low or if the buffer has reached itsfinal size and cannot be expanded again. The example code uses it inPrintBufferL() before calling Size() on the buffer (and using thereturned value to allocate a buffer of the appropriate size into which datafrom Read() is stored).
The Size() method returns the number of heapbytes allocated to the buffer, which may be greater than the actual sizeof the data contained therein, because the contents of the buffer may notfill the total allocated size. The call to Compress() before Size() thusretrieves the size of the data contained in the buffer rather than the entirememory size allocated to it.To retrieve data from the buffer, you can use the Ptr() function,which returns a TPtr8 for the given buffer position up to the end of thememory allocated. For a CBufFlat this returns a TPtr8 to the rest of thebuffer, but for CBufSeg it returns only the data from the given positionto the end of that segment.
To retrieve all the data in a segmented bufferusing Ptr(), you must use a loop which iterates over every allocatedsegment. Alternatively, as I’ve done in PrintBufferL(), the Read()method transfers data from the buffer into a descriptor, up to the length ofthe descriptor or the maximum length of the buffer, whichever is smaller.2In addition, for CBufFlat, multiple calls to InsertL() will fragment the heapwhereas a single ExpandL() or ResizeL() call will allocate all the memory required ina single contiguous block.SUMMARY1097.7 SummaryThis chapter discussed the use of the Symbian OS dynamic array classes,which allow collections of data to be manipulated, expanding as necessary as elements are added to them. Unlike C++ arrays, dynamic arraysdo not need to be created with a fixed size. However, if you do knowthe size of a collection, Symbian OS provides the TFixedArray classto represent a fixed-length array which extends simple C++ arrays toprovide bounds-checking.The chapter described the characteristics and use of the dynamiccontainer classes RArray and RPointerArray and also discussed theCArrayX classes which the RArray classes supersede.
The RArrayclasses were introduced to Symbian OS for enhanced performance overthe CArrayX classes. They have a lower overhead because they do notconstruct a TPtr8 for each array access, have fewer assertion checks andno leaving methods and are implemented as R classes, which tend to havea lower overhead than C classes. The RArray classes also have improvedsearch and sort functionality and should be preferred over CArrayXclasses.
However, the CArrayX classes may still be useful when dealingwith variable-length elements or segmented memory, because there areno RArray analogues.The chapter also discussed the descriptor array classes, CPtrC8Arrayand CPtrC16Array, and the dynamic buffers, CBufFlat andCBufSeg.All the dynamic array and buffer classes in Symbian OS are based onthe thin template idiom (see Chapter 19). The use of lightweight templatesallows the elements of the dynamic arrays to be objects of any type, suchas pointers to CBase-derived objects, or T and R class objects.8Event-Driven Multitasking Using ActiveObjectsLight is the task where many share the toilHomerActive objects are a fundamental part of Symbian OS.
This chapterexplains why they are so important, and how they are designed forresponsive and efficient event handling. Active objects are intended tomake life easy for application programmers, and this chapter alone givesyou sufficient knowledge to work with them within an application framework or derive your own simple active object class. Chapter 9 will be ofinterest if you want to write or work with more complex active objects:it discusses the responsibilities of active objects, asynchronous serviceproviders and the active scheduler in detail, and reviews the best strategiesfor long-running or low-priority tasks.
System-level programmers wishingto understand the Symbian OS client–server architecture and lower-levelsystem design should read both this chapter and the following one.8.1 Multitasking BasicsFirst of all, what are active objects for? Well, let’s go back to basics.Consider what happens when program code makes a function call torequest a service. The service can be performed either synchronously orasynchronously.
When a synchronous function is called, it performs aservice to completion and returns directly to its caller, usually returning anindication of its success or failure (or leaving, as discussed in Chapter 2).An asynchronous function submits a request as part of the function calland returns to its caller – but completion of that request occurs sometime later. Before the request completes, the caller may perform otherprocessing or it may simply wait, which is often referred to as ”blocking”.Upon completion, the caller receives a signal which indicates the successor failure of the request.