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

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

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

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

It is equivalent to callingZeroTerminate() and then Ptr(). For example:void ZeroTerminationExample(){_LIT(KMyString,"My string");TBuf<20> buf(KMyString);const TText *str;str = buf.PtrZ();/* str now points to a 16 bit NULL terminated string */_LIT(KFormat1,"str=%s\n");console->Printf(KFormat1,str);const unsigned char *nStr;TBuf8<20> buf8;buf8.Copy(buf); /* copy 16 bit string into 8-bitDESCRIPTOR METHODS197descriptor (converts to 8-bit chars)*/nStr = buf8.PtrZ();/* nStr points to a standard C style narrow string (can’t* print out directly with console->Printf)*/}The output is:str=My stringSetting the descriptor sizeYou can manually change the length of a modifiable descriptor usingSetLength() and SetMax(). Note that both of these only modify thelength stored in TDes, and not the maximum length stored in TDesC (thename SetMax() is misleading).SetLength() changes the current length of the descriptor data.

Ifyou lower the length, for example, you effectively chop off data from theend of the buffer. Zero() is equivalent to SetLength(0). The currentlength also determines where data will be appended.SetMax() will set the current buffer length value (the one stored inTDesC) to equal the maximum buffer size (also stored in TDes).

Whydo this? Typically, you use SetMax() when assigning an external buffer(e.g., char * buffer) to a pointer descriptor.For example, assume you have a char * buffer called externalBuf,and its size is buffSize. You can assign this buffer to a descriptor asfollows:TPtr myDes(externalBuf,buffSize);This will cause myDes to point to externalBuf correctly and themaximum buffer size stored in TDesC is also correct.

However, theactual size of the descriptor as specified in TDes (the size returned bySize() and Length() and where append operations would start) is 0after this line. So if you pass this descriptor to a function, or otherwiseoperate on it, it will treat this descriptor like an empty one.To solve this, call:myDes.SetMax()after the declaration. This will set the descriptor size to the maximum size(to buffSize in the example).198STRINGS, BUFFERS, AND DATA COLLECTIONS6.4.3 Using a Descriptor as an ArrayYou can use the descriptor’s [] operator to access your descriptor datain the same way you would do with a C array. Here is an example usinga binary buffer (of course, strings can also be used):void ArrayIndexExample(){_LIT(KString1,"This is my string");TChar c;TBuf<20> str(KString1);/* character access using [ ] */_LIT(KFormat1,"str[0]=%c str[3]=%c\n");console->Printf(KFormat1,str[0],str[3]);/* Binary buffer access using [] */TUint8 binData[6] = {0xB0,0xB1,0xB2,0xB3,0xB4,0xB5};TBuf8<sizeof(binData)> binDes;binDes.Copy(binData,sizeof(binData));_LIT(KFormat2,"binDes[0]=%x binDes[1]=%x binDes[5]=%x\n");console->Printf(KFormat2, binDes[0] , binDes[1] , binDes[5] );}The output of the code is:str[0] = T str[3] = sbinDes[0] = b0 binDes[1] = b1 binDes[5] = b5As you can see from the example, the [] operator can be used to readdescriptor data as if it were a standard C-style array.

You may wonderwhy a binary buffer would be put into a descriptor like this, since it wasan array already. The reason is that having it as a descriptor provides safeaccess and will raise a panic immediately if you go over the end of thearray. Try it and see.You can also write descriptor data (if it’s a modifiable descriptor) usingthe [] operator.6.5 Converting Between 8-Bit and 16-Bit DescriptorsYou may have 8-bit strings that need to be in the form of a 16-bit descriptor.

You can convert the 8-bit descriptor to a 16-bit descriptor by callingthe Copy(TDesC8&) method of the 16-bit descriptor – this will expandeach 8-bit data value to 16 bits, setting the high-order bytes to zero.This is straightforward and may be suitable for simply getting a narrowstring in the correct format – however, if the 8-bit string is coded inUTF-8, this simple 8-bit to 16-bit conversion will not work correctly. Thisis because the multi-byte sequences of the string will just be copied as is,resulting in a corrupted 16-bit string.DYNAMIC BUFFERS199The API class CnvUtfConverter is used to translate between UTF-8and Unicode. The class contains two methods to do this:CnvUtfConverter::ConvertToUnicodeFromUtf8(src8,dest16)where src8 is an 8-bit descriptor containing the UTF-8 string anddest16 is the 16-bit descriptor where the converted Unicode string willbe put;CnvUtfConverter::ConvertFromUnicodeToUtf8(dest8,src16)where src16 is the 16-bit descriptor that contains the Unicode stringand dest8 is the 8-bit descriptor where the UTF-8 string is placed.Make sure you include utf.h in your source file and charconv.libin the LIBRARY statement of the MMP file when using these functions.6.6 Dynamic BuffersCBufBase, CBufSeg, and CBufFlat are API classes used for managingexpandable buffers known as dynamic buffers.

While a descriptor hasa fixed-size buffer allocated to it, a dynamic buffer can be resized asneeded at runtime – and in some cases this resizing is automatic as youadd more data.Figure 6.16 shows the class hierarchy for dynamic buffers, along withtheir methods.6.6.1 When Should I Use Dynamic Buffers?Use dynamic buffers when you do not know what the maximum size ofthe buffer will be. Use descriptors if you do know the size, or can specifya maximum size big enough that you can be sure it will not be exceededat runtime (although this can waste memory, or cause a panic if you guesswrongly).Dynamic buffers are not used much directly, but are used by otherAPIs, including collection classes such as the array API classes (seesection 6.7).6.6.2Flat and Segmented BuffersCBufFlat and CBufSeg represent the two types of dynamic buffers: flatand segmented.

From an API perspective, these buffers act virtually thesame – they implement the abstracted dynamic buffer interface provided200STRINGS, BUFFERS, AND DATA COLLECTIONSCBufBaseRead()Size()Ptr()Compress()CBufFlatNewL()BackPtr()Compress()SetReserveL()Ptr()Capacity()Delete()Delete()Write()Reset()Resize()Expand()Inset()BackPtr()CBufSegNewL()BackPtr()Compress()Ptr()Delete()Figure 6.16 Dynamic Buffer Class Diagramby CBufBase. It’s instructive to understand them though, so that you canchoose the most efficient dynamic buffer type for your situation.Flat buffers are allocated as a single memory region on the heap. Asmore space in the buffer is needed, the single cell is reallocated to abigger size.To create a flat buffer, call CBufFlat::NewL(aGranularity),where granularity is the number of bytes by which the buffer size isincreased (or decreased) at one time. For example, if your granularity is512, then 512 bytes are initially allocated on the heap before the firstdata is written.

An allocation of 512 more bytes occurs when you writepast the 512th byte. The buffer is increased again by another 512 byteswhen you write past the 1024th byte, and so on.The advantage of flat buffers is that the memory is always contiguous,and thus is more straightforward and efficient to access. However, bufferexpansions are expensive, since they involve a reallocation – whichrequires the data to be copied to a new heap cell.Therefore, use flat buffers for buffers that need to be expanded atruntime, but where expansions are rare.Unlike a flat buffer, a segmented dynamic buffer allocates a newmemory region on the heap when more buffer space is needed, as opposedto performing an allocation of a single heap region.

Thus, segmentedbuffers are more efficient when expanding. In addition, segmented buffersare more efficient when inserting and deleting data since the shuffling ofdata can be minimized.DYNAMIC BUFFERS201To create a segmented buffer, call CBufSeg::NewL(aGranularity), where granularity is the number of bytes in a segment.While a segmented buffer can be expanded much more efficiently thana flat buffer, the disadvantage is that the region is not contiguous and thusmay be more difficult to access, depending on how you use the buffer.Note that, although the buffer is not contiguous, this fact is hiddenwhen accessing the buffer through the dynamic buffer class methods.CBufFlat and CBufSeg map the position value to the memory addresstransparently.

Only when you manipulate the memory buffer directly(i.e., by using a pointer returned by the Ptr() method) will you need tobe concerned about the buffer being segmented.6.6.3 Dynamic Buffer MethodsLet’s briefly look at the key methods that are available to both segmentedand flat buffers through the abstract interface of CBufBase. Consult theSymbian OS Library in the SDK documentation for more details of howthese APIs are used.Reading and writing a dynamic bufferThe methods Read() and Write() allow you to read from and write toa dynamic buffer starting at a specified position. The data is read into orwritten from an 8-bit descriptor, or a raw memory region specified by apointer and the data size.

For example:void DynamicBufferExampleL(){TUint8 dataAry1[100];TUint8 dataAry2[100];TUint8 outAry[120];// initialize dataAry1 and dataAry2 with some stuffTUint8 j=100;for (TUint8 i=0; i<100; i++){dataAry1[i]=i;dataAry2[i]= j--;}TPtrC8 desAry1(dataAry1,100); // create descriptor for dataAry1CBufFlat* dynBuf = CBufFlat::NewL(20);CleanupStack::PushL(dynBuf);dynBuf->ResizeL(100);// allocate memory to buffer, none to startdynBuf->Write(0,desAry1);// write desAry1 to// dynBuf starting at position 0.dynBuf->Write(3,dataAry2,50); // write first 50 bytes of dataAry2 to// dynBuf at position 3dynBuf->Read(0,outAry,50);// reads 50 bytes starting at// position 0, putting data into buffer// to outAry_LIT(KFormat1,"dynbuf pos=%d : %d %d %d %d %d\n");console->Printf(KFormat1,0,202STRINGS, BUFFERS, AND DATA COLLECTIONSoutAry[0],outAry[1],outAry[2],outAry[3],outAry[4]);dynBuf->ResizeL(120);// add some room to the bufferdynBuf->Write(90,dataAry1,30);dynBuf->Read(100,outAry,20);console->Printf(KFormat1,100,outAry[0],outAry[1],outAry[2],outAry[3],outAry[4]);CleanupStack::PopAndDestroy();}Output:dynbuf pos=0: 0 1 2 100 99dynbuf pos=100 : 10 11 12 13 14The code above should be self-explanatory.

One thing to note is thatsince Write() does not expand the buffer automatically, the methodResizeL() is used to allocate memory to the buffer.Inserting and deleting dataYou can insert data into, and delete data from, a dynamic buffer by usingthe InsertL() and Delete() methods for the dynamic buffer class.InsertL() acts the same as a Write() except that the data currentlyin the buffer at the insertion point is shifted up in position. Also, unlikewith Write(), InsertL() will expand the buffer, if necessary, to makeroom for the new data.So if the line:dynBuf->Write(90,dataAry1,30);was replaced in the previous example by:dynBuf->InsertL(90,dataAry1,30),then the ResizeL() would not be needed since InsertL() would seethat more room is needed in the buffer and resize accordingly.

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

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

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

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