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

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

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

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

Let’s start our discussion ofheap descriptors with HBufC.HBufC descriptorHBufC is a non-modifiable descriptor class that is allocated entirely on theheap and referenced as a pointer. HBufC provides a static New() methodfor instantiating a HBufC. The following line shows how to create one:HBufC* myDes=HBufC::New(100);THE DESCRIPTOR CLASSES181This line will allocate a 16-bit descriptor on the heap with a buffer lengthof 100 characters (200 bytes).NewL() and NewLC() methods are also available so you don’t haveto check the validity of the returned pointer because they leave on error.NewLC() pushes a created pointer onto the cleanup stack.In memory, an HBufC looks just like a TBufC (see Figure 6.14).The type field for HBufC is set to 0 as for TBufC, since it appears likeTBufC in memory.You may wonder why you cannot just use a pointer to a TBufC insteadof having another class – like the following:TBufC<100>* myDes = new TBufC<100>;This also works, but HBufC should be used.

The reason is that HBufC provides some extra methods for dealing with the heap. For example, HBufChas a method called ReAlloc(). ReAlloc(TInt aMaxLength) creates a new descriptor on the heap, of size aMaxLength, copies thedescriptor data to it and deletes the old one. The ReAlloc() functionreturns a new pointer to the heap descriptor to reflect the new allocation.ReAlloc() returns NULL if an error has occurred. A ReAllocL() function also exists, which is the same as ReAlloc() except the functionleaves on errors.Modifying HBufC dataYou can modify the data in a HBufC buffer by using the Des() method.Des() returns a TPtr whose buffer pointer is initialized to point tothe heap-based buffer in the HBufC descriptor. Since the returned TPtrdescriptor is a modifiable descriptor, you can use it to write the heapdescriptor’s data buffer. An interesting feature is that as you change theHBufC data via this TPtr, the buffer size in the TPtr descriptor and theHBufC whose data it is pointing to, are both updated.HeapHBufCHBufC*type iLengthFigure 6.14 HBufC Memory LayoutiBuf182STRINGS, BUFFERS, AND DATA COLLECTIONSHeapHBufCHBufC*type iLengthiBufTPtrreturned from HBufC::Des()type iLength iMaxLengthiPtrFigure 6.15 HBufC’s Des() MethodSee Figure 6.15 for how the TPtr returned by Des() is related toHBufC.

The maximum length of TPtr is set to the length of the allocatedHBufC buffer passed in the New() function. As data is changed, bothlengths in HBufC and TPtr are updated together.Let’s look at the HBufC example shown below.void HeapDesExampleL(){_LIT(KString1,"Test");_LIT(KString2,"My Heap String");HBufC* myHeapDes = HBufC::NewL(KString1().Length());CleanupStack::PushL(myHeapDes);*myHeapDes = KString1;_LIT(KFormat1,"myHeapDes = \"%S\"length = %d\n");console->Printf(KFormat1,myHeapDes,myHeapDes->Length());myHeapDes = myHeapDes->ReAllocL(KString2().Length());//if you do not do this,the next line executed would panic//Replace entire string in the HBufC*myHeapDes = KString2;console->Printf(KFormat1,myHeapDes,myHeapDes->Length());//Get a modifiable pointer to the HBufC’s data bufferTPtr myPtr = myHeapDes->Des();_LIT(KString3,"Hello");_LIT(KString4,"!!!");// Modify the HBufC through TPtr, using Copy() and Append()myPtr.Copy(KString3);myPtr.Append(KString4);_LIT(KFormat2,"myHeapDes = \"%S\"length = %d myPtr = \" %S\ "length =%d\n");THE DESCRIPTOR CLASSES183console->Printf(KFormat2,myHeapDes,myHeapDes->Length(),&myPtr,myPtr.Length());CleanupStack::PopAndDestroy(myHeapDes);}The output from the example is as follows:myHeapDes = "Test" length = 4myHeapDes = "My Heap String" length = 14myHeapDes = "Hello!!!" length = 8 myPtr = "Hello!!!" length = 8The example code first allocates a HBufC with a buffer big enough tofit the string "Test".

It is then assigned that string. The buffer is thenreallocated using the ReAllocL() method and set to a bigger string.The return value of ReAllocL(), which is the pointer to the newlyallocated descriptor, is written to myHeapDes. The example then showshow to modify the buffer using a modifiable TPtr returned from theHBufC::Des() method. Notice in the last output lines that the lengthsof both the TPtr and the HBufC descriptors are updated and that theydo indeed both point to the same, changed data.Creating a HBufC descriptor from another descriptorTDesC provides a method called Alloc(), which will create a heapdescriptor and initialize it with the data of the descriptor on whichAlloc() was called. For example:TBuf<80> myStr(_L("Some string data"));HBufC* myHeapDes;myHeapDes=myStr.Alloc();Given sufficient available memory, the above code creates a heap descriptor initialized with the contents of myStr ("Some string data"), andassigns it to myHeapDes. You can also call Alloc() on a literal.

Forexample, the following code creates a heap descriptor and initializes itwith the contents of KMyString:_LIT(KMyString, "My string");HBufC* myHeapDes;myHeapDes = KMyString().Alloc();AllocL() and AllocLC() versions of the Alloc() function also exist,which will leave on allocation failures and, in the case of AllocLC(),push the allocated heap descriptor on the cleanup stack. Alloc() willreturn NULL if the memory allocation fails.184STRINGS, BUFFERS, AND DATA COLLECTIONSRBuf descriptorLike HBufC, an RBuf’s data buffer resides on the heap; however, insteadof calling a ‘new’ method to create the descriptor, you instantiate RBufon the stack as an automatic variable.

Internally, RBuf will allocate buffermemory on the heap (using RBuf Create()), or it may take ownershipof preallocated heap memory, including a HBufC or another RBuf (usingthe RBuf Assign() method).Like other R classes, RBuf has a Close() method. RBuf’s Close()method will free the data buffer on the heap owned by the descriptor.Always remember to call Close() when you are finished with the RBufdescriptor data, or a memory leak will occur.Below is a simple example of using RBuf:RBuf myBuff;myBuff.CreateL(100) ;myBuff.Copy(_L("My RBuf data"));...myBuff.Close();The CreateL() method allocates a buffer on the heap (a buffer oflength 100 in this case) for your data.

A leave will occur if thereis a problem creating the data buffer. Alternatively, you can call theCreate() method, where an error would be indicated in the functionreturn code instead of as a leave.RBuf is derived from TDes, and thus acts like any other descriptor,allowing you to pass it to functions that take TDes descriptors as input,and for you to access all read and write descriptor methods (i.e., TDesCand TDes methods). In this example, I copy the string "My RBuf data"into the descriptor using the Copy() method.Using RBuf::CleanupClosePushL()The myBuff.Close() at the end of the previous example frees theallocated buffer belonging to the myBuff descriptor.

However, what ifa leave occurs after the buffer is allocated and before the Close() iscalled? In that case the memory is not freed, which is not desirable.A better and safer way to invoke RBuf::Close() is by using RBuf’sCleanupClosePushL(), which takes advantage of the cleanup stackto provide leave-safe code, like below:RBuf myBuff;myBuff.CleanupClosePushL();// more code here, can leave on errors// finished using myBuffCleanupStack::PopAndDestroy(myBuff);THE DESCRIPTOR CLASSES185CleanupClosePushL() pushes the RBuf object as a cleanup itemon the cleanup stack. After calling this function, a leave, or a call toCleanupStack::PopAndDestroy() – whichever occurs first – willinvoke Close() automatically.Creating RBuf from another descriptorYou can have your RBuf descriptor allocate memory and initialize itwith a copy of the contents of another descriptor using variations of theCreateL()/Create() methods.

Below is an example:TBuf<100> myTbuf(_L("TBuf stuff"));RBuf myRbuf1;myRbuf1.CreateL(myTbuf);myRbuf1.CleanupClosePushL();RBuf myRbuf2;myRbuf2.CreateL(myTbuf,500); //copies myTbuff, but allocates buffer of//length 500 instead of myTbuf lengthmyRbuff2.CleanupCLosePushL();// more code here, can leave on errorsCleanupStack::PopAndDestroy(2,myRbuf1);The prototype of the CreateL() functions used above are: CreateL(TDesC& aDestoCopy) and CreateL(TDesC& aDesToCopy,TInt aMaxLength).Taking ownership of preallocated buffersInstead of creating its own buffer, an RBuf descriptor can take ownershipof a buffer already allocated on the heap. RBuf’s Assign() methodaccomplishes this.

What exactly does taking ownership of a buffer mean?It means that the RBuf object uses the assigned preallocated buffer as itsown and is now responsible for freeing it when it is finished (i.e., whenits Close() method is called).Here is an example:TInt bufferSize=100;TUint16 buff=static_cast<TUint16*>(User::AllocL(bufferSize*sizeof(TUint16)));RBuf myRbuf;myRbuff.CleanupClosePushL();myRbuf.Assign(buff,bufferSize);// ...

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

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

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

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