Главная » Просмотр файлов » Symbian OS Explained - Effective C++ Programming For Smartphones (2005)

Symbian OS Explained - Effective C++ Programming For Smartphones (2005) (779885), страница 25

Файл №779885 Symbian OS Explained - Effective C++ Programming For Smartphones (2005) (Symbian Books) 25 страницаSymbian OS Explained - Effective C++ Programming For Smartphones (2005) (779885) страница 252018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 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.

Характеристики

Тип файла
PDF-файл
Размер
2,53 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Как Вы думаете, сколько людей до Вас делали точно такое же задание? 99% студентов выполняют точно такие же задания, как и их предшественники год назад. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6264
Авторов
на СтудИзбе
317
Средний доход
с одного платного файла
Обучение Подробнее