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

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

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

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

(As I described in Chapter 5,the length of a descriptor cannot be greater than 228 bytes because the topfour bits of the length word are reserved to indicate the type of descriptor.)The base class for modifiable descriptors, TDes, implements a MaxLength() method which returns the maximum length allowed for thedescriptor. Beware of the SetMax() method, which doesn’t allow youto change the maximum length of the descriptor, thereby expandingor contracting the data area; instead, it sets the current length of thedescriptor to the maximum length allowed.You can use SetLength() to adjust the descriptor length to anyvalue between zero and its maximum length (inclusively).

The Zero()method also allows you to set the length to zero. If you thought thatmethod might fill the contents of the descriptor with zeroes, you wantthe FillZ() method – which is overloaded so you can fill the entiredescriptor or to a required length. If you don’t want to fill with zeroes,the overloaded Fill() methods permit you to choose which characterto fill the descriptor.3TDes also has the PtrZ() method, which returns a pointer to the first character in thedata array and appends a NULL terminator to the descriptor data so the returned pointer canbe used directly as a C string.

(The length of the descriptor must be less than its maximumallowable length in order for there to be sufficient space for the zero terminator.)80GOOD DESCRIPTOR STYLETDes implements an overloaded set of Copy() methods, two ofwhich are shown below. (There are another six overloads of the Copy()function, which allow copying directly from a NULL-terminated string orfrom a pointer directly into descriptor data and which perform folding,collation or case adjustment as part of the copy.)IMPORT_C void Copy(const TDesC8 &aDes);IMPORT_C void Copy(const TDesC16 &aDes);These methods copy the descriptor parameter into the data area of thedescriptor on which they are called, setting its length to reflect the newdata.

The methods will panic if the maximum length of the receivingdescriptor is shorter than the incoming data. The Copy() method isoverloaded to take either an 8- or 16-bit descriptor. Thus, not onlyis it possible to copy a narrow-width descriptor onto a narrow-widthdescriptor and a wide descriptor onto a wide descriptor, but it is alsopossible to copy between descriptor widths, effecting a conversion ofsorts in the process.These methods are an example of where the implementation of theTDes8 class differs from the TDes16 class. As Figure 6.2 illustrates, theCopy() method implemented by TDes8 to copy an incoming wide16-bit descriptor into a narrow descriptor strips out alternate characters,assuming them to be zeroes, that is, the data values should not exceed255 (decimal).

The Copy() method which copies a narrow descriptorinto the data area is a straight data copy, however.// Instantiate a narrow descriptorTBuf8<3> cat(_L8("cat")); // _L is described in Chapter 5// Instantiate a wide descriptorTBuf16<3> dog(_L16("dog"));// Copy the contents of the wide descriptor into the narrow descriptorcat.Copy(dog); // cat now contains "dog"catCdogATDTDes8\0Ocat.Copy(dog)Strips \0 padding\0G\0TDes16catDOGFigure 6.2 NULL characters are stripped out when wide characters are copied into anarrow descriptorCOMMON DESCRIPTOR METHODS81Conversely, for class TDes16, an incoming 16-bit descriptor can becopied directly onto the data area, but the Copy() method that takes an8-bit descriptor pads each character with a trailing zero as part of thecopy operation, as shown in Figure 6.3.

The Copy() methods thus forma rudimentary means of copying and converting when the character setis encoded by one 8-bit byte per character and the last byte of each widecharacter is simply a NULL character padding.// Instantiate a narrow descriptorTBuf8<5> small(_L8("small"));// Instantiate a wide descriptorTBuf16<5> large(_L16("large"));// Copy the contents of the narrow descriptor into the widelarge.Copy(small); // large now contains "small"smallDSlarge\oMOAL\oGLLTDes8\0A\0R\0G\0E\0TDes16large.Copy(small)Adds \0 paddinglargeSFigure 6.3\0M\0A\0L\0L\0NULL characters pad narrow characters when copied into a wide descriptorTo perform proper conversion in both directions between 16-bit Unicode and 8-bit, non-Unicode, character sets (or between Unicode andthe UTF-7 and UTF-8 transformation sets) you should use the conversion library (charconv.lib) that Symbian OS provides (see headerfile charconv.h).

You can also use the Character Conversion Plug-inProvider API to write plug-in DLLs to extend the range of foreign charactersets beyond the ones already provided by Symbian OS. I’ll discuss theuse of a framework and plug-ins, a commonly used Symbian OS idiom,in more detail in Chapter 13.Symbian OS has been built as _UNICODE since the v5U release.The descriptor classes which end in 8 or 16 reflect the charactersize of the descriptor. The neutral versions, with no numerical indicator, are implicitly 16-bit and, for many descriptor operations, youcan simply use this neutral version, which will, if nothing else, makeyour code more readable. However, there are occasions when youare dealing with text of a specific character size. For example, youmay be working with 8-bit text (e.g. an ASCII text file or Internetemail – or simply using the RFile::Read()and RFile::Write()82GOOD DESCRIPTOR STYLEmethods shown above) for which you should explicitly use the 8-bitdescriptor classes, using TText8 pointers as returned by the Ptr()operation to access characters.

When working with 16-bit text (forexample, Java strings), you should indicate the fact explicitly by usingthe TDesC16-derived classes, referencing individual characters withTText16 pointers.As I described in Chapter 5, because descriptors do not use NULLterminators, they may be used with binary data as well as strings, whichalso allows code re-use within Symbian OS. Binary data is alwaysconsidered to be 8-bit and you should use the 8-bit classes to manipulateit, using TInt8 or TUint8 to reference individual bytes.6.3 The Use of HBufC Heap DescriptorsHaving discussed some of the features of the descriptor classes, I’llmove on now to discuss some of the common mistakes made when usingdescriptors.

First I’ll cover the creation and use of HBufC heap descriptors.As I mentioned in Chapter 5, HBufC can be spawned from existingdescriptors using the Alloc() or AllocL() overloads implementedby TDesC. Here is a contrived example which shows how to replaceinefficient code with AllocL():void CSampleClass::UnnecessaryCodeL(const TDesC& aDes){iHeapBuffer = HBufC::NewL(aDes.Length());TPtr ptr(iHeapBuffer->Des());ptr.Copy(aDes);...// could be replaced by a single lineiHeapBuffer = aDes.AllocL();}Another common way to introduce complexity occurs in the oppositedirection, that is, the generation of TDesC& from a heap descriptor.

Acommon mistake is to call the Des() method on the heap descriptor; thisis not incorrect (it returns a TDes&), but it is clearer and more efficientsimply to de-reference the HBufC pointer when a non-modifiable TDesC&is required:const TDesC& CSampleClass::MoreAccidentalComplexity(){return (iHeapBuffer->Des());// could be replaced more efficiently withreturn (*iHeapBuffer);}THE USE OF HBufC HEAP DESCRIPTORS83Another subtle problem occurs when you allocate an HBufC and thencall Des() on it to return a TPtr. If you recall, an HBufC object doesn’thave a maximum length word – since it is non-modifiable, it doesn’t needone. But the modifiable TPtr does. The length of the TPtr is set to thestored length of the HBufC, but where does the maximum length comefrom when you create it? In fact, when you call Des() on HBufC, it usesthe maximum length of the heap cell in which the HBufC was allocatedto set the maximum length of the returned TPtr.The maximum length of the heap cell may not be exactly whatyou specified as the maximum length of the heap descriptor when youallocated it.

This may happen because you didn’t specify a word-alignedmaximum length (i.e. a multiple of 4 bytes) or because there was notenough space left over in the free cell from which the heap cell wasallocated to create any other heap cells. The minimum size required fora heap cell is approximately 12 bytes and, if there are fewer bytes leftover, your descriptor will be given the extra bytes too. (The former caseof specifying an unaligned maximum length is much more common.) Theend result in either case is that the maximum length of a TPtr returnedfrom a call to HBufC::Des() may not be exactly the size you asked forwhen you allocated the heap descriptor; while it will not be truncated,it could be longer. Don’t get caught out by the fact that it may be largerthan you expect – but, likewise, don’t expect that it is simply rounded upto the next word-aligned value.

For example:HBufC8* buf = HBufC8::NewLC(9);TPtr8 ptr(buf->Des());TInt maxLength = ptr.MaxLength(); // maxLength>9 but may not be 12In practice this will be guaranteed to fill ptr with at least three extrabytes but beyond that, you cannot predict how much larger the maximumlength of the heap buffer is than requested. Since you cannot guaranteethe value of the maximum length, stick to using the Length() methodsof the TPtr or HBufC, or the value you used to allocate the HBufCinitially.Here’s an example where you could get caught out, illustrating the useof pointers to manipulate the contents of a descriptor and the use of anassertion statement to catch access beyond the descriptor length:_LIT(KPanic, "TestPointer");const TInt KBufferLength = 10;void TestPointer(){// Create a buffer with length KBufferLength = 10 bytesHBufC8* myBuffer = HBufC8::NewMaxL(KBufferLength);TPtr8 myPtr(myBuffer->Des());myPtr.Fill(’?’); // Fill with ’?’84GOOD DESCRIPTOR STYLE// Byte pointer to descriptor in memoryTUint8* ptr = (TUint8*)myPtr.Ptr();TInt maxLength = myPtr.MaxLength();for (TInt index = 0; index < maxLength; index++){// This fails at the end of the buffer (index = 10)// because myPtr.MaxLength() > KBufferLength__ASSERT_DEBUG(index<KBufferLength,User::Panic(KPanic, KErrOverflow));(*ptr) = ’!’; // Replace the contents with ’!’++ptr;}}A common mistake is to call the Des() method on the heap descriptor to return a TDes&.

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

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

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

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