Главная » Просмотр файлов » Wiley.Developing.Software.for.Symbian.OS.2nd.Edition.Dec.2007

Wiley.Developing.Software.for.Symbian.OS.2nd.Edition.Dec.2007 (779887), страница 36

Файл №779887 Wiley.Developing.Software.for.Symbian.OS.2nd.Edition.Dec.2007 (Symbian Books) 36 страницаWiley.Developing.Software.for.Symbian.OS.2nd.Edition.Dec.2007 (779887) страница 362018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 36)

This is why L is not as efficient as LIT (remember thatLIT involves no runtime initialization). L, however, is sometimes moreconvenient since you do not need a separate line to define the literal(e.g., User::PrintInfo(L("Hello"))).L is officially deprecated, and is recommended for use only in cases(such as in test code) where source clarity is more important than runtimeefficiency. That being said, support is likely to continue for the foreseeablefuture.Figure 6.3 below compares how literals created with LIT and L arestored in memory._LIT (KHello, "Hello World!")TPtrC hello (_L("Hello World!"))ROMStackTemporary12iLength12Hello World!\0Figure 6.3iPtrROMHello World!\0Memory Layout for Literal Descriptors6.3.3 Buffer DescriptorsTBuf and TBufC are buffer descriptors, that is, they contain their databuffers within their classes.

The buffer’s size is specified by an integerpassed as a template argument during the class declaration. Referencesection 6.7 for more details on templates and how Symbian OS uses them.For example, TBuf<10> buf creates a 16-bit descriptor object thatcontains a buffer big enough for ten 16-bit values (20 bytes).

For 8-bitdescriptors, the value specifies the number of 8-bit values allocated, soTBuf8<10> buf would allocate 10 bytes rather than 20.TBuf and TBufC are commonly used for small buffers and are oftendeclared on the stack as automatic variables. You can think of them asarrays – in fact, these classes implement their data buffers as memberarrays, whose size is determined from the template argument.TBuf is modifiable – it inherits from both TDesC and TDes and thushas both the read-only (TDesC) methods and the read/write (TDes)descriptor methods available to it. TBufC, however, inherits only fromTDesC, and therefore has only the read-only TDesC methods available to it.17432 bits(From TDesC)typeiLengthSTRINGS, BUFFERS, AND DATA COLLECTIONS32 bits(From TDes)iMaxLengthiMaxLength character(From TBuf)iBuf4 bitsFigure 6.4 TBuf Memory LayoutFigure 6.4 shows how a TBuf descriptor appears in memory.The fields labeled type and iLength make up a 32-bit value declaredas part of TDesC (type is a 4-bit value that specifies the type of descriptorthat this memory region represents).

The value of type is 3 for TBufdescriptors.The length of the data currently in the data buffer is indicated by a28-bit value, shown in Figure 6.4 as iLength. This is the value returnedby the Length() method (in units of data width) and Size() method (inbytes). The actual size of the allocated buffer is stored in iMaxLength,which is a 32-bit value that comes from class TDes. It is used toprevent the buffer from being accessed beyond the buffer’s boundary.The allocated data buffer array is shown by iBuf – it is declared in theTBuf class itself.You may wonder why type is stored with the descriptor in TDesC.If the descriptor methods in TDes and TDesC are declared virtual andthe derived classes override the functions as needed, then this type ofinformation should not be needed.

That would be correct – except thatvirtual functions are not used in descriptors. Descriptors were written tobe space-efficient, and virtual functions are more of an overhead than juststoring the 4-bit type. The descriptor methods in TDes and TDesC usethe Ptr() method, which contains a switch statement on the typevalue to perform the locate to the descriptor data area correctly for thespecified descriptor.Let’s step through some TBuf operations and show how memory ishandled.When you declare the TBuf as:TBuf<10> buf;the descriptor in memory appears as shown in Figure 6.5.The type value is set to indicate a TBuf (3), the length is zero, sinceno data is yet in the buffer and the maximum length is equal to theTHE DESCRIPTOR CLASSES175allocated buffer size of 10.

The buffer data is shown as a row of Xs, whichindicate uninitialized memory.30Figure 6.5xxxxxxxxxx10Initial State of TBuf<10>To copy some data to it, you can pass a value to the TBuf constructorwhen declared as in the following lines:_LIT(KString, "Test");TBuf<10> buf(KString);or use the Copy() method as follows:_LIT(KString, "Test");TBuf<10> buf;buf.Copy(KString);Both will result in the descriptor appearing in memory as shown inFigure 6.6.3410TestxxxxxxFigure 6.6 Copying Data to TBufNow let’s append some data by adding the following:_LIT(KString1, "!!! ");buf.Append(KString1);Append() will append the data to the descriptor buffer starting at thecurrent length.

The length is updated appropriately. The descriptor willnow look as in Figure 6.7.176STRINGS, BUFFERS, AND DATA COLLECTIONS3710Figure 6.7Test!!!xxxAppending to TBufIf you then add the following:_LIT(KString2, "1234");buf.Append(KString2);what happens? A panic occurs, since this would write past the end of theallocated buffer.A TBufC descriptor is declared in the same way as a TBuf descriptor.A TBufC descriptor, however, is not modifiable, with the followingexception – data can be completely replaced in the buffer by usingassignment through the = operator.Figure 6.8 shows how TBufC is stored in memory.32 bits(From TDesC)typeAllocated Length(From TBufC)iBufiLength4 bitsFigure 6.8 TBufC Memory LayoutNote that TBufC has only one length value (from TDesC) stored inmemory instead of two as in TBuf. A type value of 0 indicates TBufC.If you declare a TBufC as follows:_LIT(KString1, "Sam");TBufC<10> cBuf(KString1);the memory layout will be as shown in Figure 6.9.You cannot add to the buffer with a non-modifiable descriptor; however – as mentioned – you can replace it.

For example, you can add theTHE DESCRIPTOR CLASSES177following to the previous code to reassign the buffer data from KString1("Sam") to KString2 ("Merry"):_LIT(KString2, "Merry");cBuf=KString2;30SamxxxxxxxFigure 6.9 TBufC containing "Sam"05MerryxxxxxFigure 6.10 TBufC containing "Merry"The descriptor memory will then appear as in Figure 6.10.What if you try to replace a TBufC string with one that is too bigfor the buffer? Since no maximum size is stored with the descriptor, willit allow you to overwrite the buffer? The answer is no, it will cause apanic, as it would on a TBuf.

The = operator uses the maximum valuethat is supplied at compile time via the template argument – no storagerequired – to see if the buffer would be overwritten.You may then wonder why modifiable descriptors need to store themaximum size value. It’s because, most times, modifiable descriptors areoperated on from base class pointers (TDes) and thus will not know thetemplate size passed over and must rely on a member variable to knowthe allocated buffer size, to protect against overruns.6.3.4 Pointer DescriptorsPointer descriptors behave like buffer descriptors except that they containa pointer to an external data buffer instead of the data buffer itself. TPtrand TPtrC are pointer descriptors.TPtr is a modifiable pointer descriptor and is stored in memory asshown in Figure 6.11.You can see that the TPtr descriptor memory looks similar to TBufexcept that the buffer resides outside the descriptor.

The type field is setto 2 for TPtr.Figure 6.12 shows how TPtrC is stored in memory.Like its buffer descriptor counterpart TBufC, TPtrC does not storethe buffer’s maximum length (since it does not inherit from TDes). Like178STRINGS, BUFFERS, AND DATA COLLECTIONSTBufC, the buffer data also cannot be modified via this descriptor exceptby direct replacement of the data.32 bits(from TDesC)typeiLength32 bits(from TDes)32 bits(from TPtr)iMaxLengthiPtr4 bitsExternal Memory BufferFigure 6.11 TPtr Memory Layout32 bits(from TDesC)typeiLength32 bits(from TPtr)iPtr4 bitsExternal Memory BufferFigure 6.12 TPtrC Memory LayoutHow do you initially set your TPtr or TPtrC buffer pointer to pointto a memory region? The buffer pointer can be set when the pointerdescriptor is constructed.

For example:_LIT(KSting1, "some data");TBufC<10> someDes(KString1);TPtrC myDes(someDes);creates a non-modifiable pointer descriptor to the descriptor someDes.THE DESCRIPTOR CLASSES179Another example:TInt bufArray[100];TPtr myDes(bufArray,sizeof(bufArray));// constructor arguments: buffer pointer and buffer size.This will create a modifiable pointer descriptor called myDes that pointsto the buffer’s allocated memory. For a TPtr such as in this example,the size of myDes will be zero (indicating it’s empty so far), and themaximum size is the size of the array passed as the second argument.Data can then be copied and appended to the buffer using TPtr as itwould be with a TBuf descriptor._LIT(KString1, "Test");_LIT(KString2, "!!!");myDes.Copy(KString1);myDes.Append(KString2);This will result in the memory appearing as in Figure 6.13.27100PointerTest!!!Figure 6.13 TPtr After AppendIn some cases, especially if you are interfacing with ported C code,you may have a buffer that already contains data, and you want to assignit to a descriptor.

In that case, you will want the pointer descriptor tobe initialized with the length of the data in the buffer, in addition to themaximum length.This can be done within the TPtr constructor. For example:TInt buff = new malloc(100*sizeof(TInt));180STRINGS, BUFFERS, AND DATA COLLECTIONSfor (Tint i=0;i<20;i++) *buff++=i; // write some data in// 20 bytes of allocat bufferTPtr myDes(buff,20,100);...This creates a TPtr descriptor that points to the allocated buffer pointedto by buff, sets the descriptor length to 20 and the maximum length ofthe descriptor to 100.Or you can construct the TPtr/TPtrC, and then afterwards set thebuffer with Set(buff,length,max length) (only in the case ofTPtr) or Set(buff,max length) (where length would default tozero).There are other ways of pointing TPtr and TPtrC to memory regions.You can find more in the SDK documentation about the various overloaded constructors and Set() methods.6.3.5 Heap DescriptorsThis section describes the two heap descriptors, HBufC and RBuf.Both of these descriptors allocate their data buffers on the heap, andthey both allow their buffers to be resized when needed (althoughthis resizing must be done explicitly by you, the programmer; it’s notautomatic).

Unlike the other types of descriptors, you must also takeresponsibility for freeing the memory used by heap descriptors whenyou are finished using them. For HBufC this entails deleting the pointeryou assigned the HBufC object to (preferably by pushing the pointer onthe cleanup stack and calling CleanupStack::PopAndDestroy()).In the case of RBuf, you call the Close() method to free its memory(or preferably, use the RBuf CleanupClosePushL() method and thenCleanupStack::PopAndDestroy() when finished).Note that RBuf was introduced in Symbian OS v8, so it is relativelynew. Before then, HBufC was used exclusively for heap-based buffers.In general, you should use RBuf for modifiable data and HBufC fornon-modifiable data. However, you will see that there is also a way tomodify HBufC through a pointer descriptor.

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

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

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

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