Главная » Просмотр файлов » Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007

Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (779890), страница 23

Файл №779890 Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (Symbian Books) 23 страницаWiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (779890) страница 232018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

DoingHEAP DESCRIPTORS99so typically generates a compiler warning if an attempt is made to callSet().If you have a TPtr (of either type) that you wish to declare now butinitialize with data later then the Set() method is useful:TPtr ptr(NULL, 0);...ptr.Set(hbuf->Des());It is also useful if the TPtr is a member of a class:CSomeClass::CSomeClass() : iPtr(NULL, 0){}...iPtr.Set(hbuf->Des());5.6 Heap DescriptorsThe heap descriptors are HBufC and RBuf and their data is stored onthe heap.

They are responsible for the allocation and de-allocation ofthis memory. The heap descriptors are used in some situations wheremalloc() is used in C.The RBuf descriptor is new and was introduced into Symbian OS v8.0(it is documented in the Symbian Developer Library from v8.1) and somay not be present if you are using an older SDK.These types are useful when the amount of data to be held by thedescriptor cannot be determined until run time or if a large amount ofdata is required to be used as a local variable6 (the stack size is limited inSymbian OS and you should always strive to minimize its usage).With both RBuf and HBufC descriptors, if the heap size needs toexpand, this is not done automatically and you must dynamically resizethe descriptor.With both HBufC and RBuf descriptors, you are responsible for memory management so always be aware of cleanup issues to ensure thatthere is no risk of memory leaks.

HBufCs are placed on the cleanupstack using an overload of CleanupStack::PushL(), while RBufshave their own method for pushing to the cleanup stack: RBuf::CleanupClosePushL().6If you have a very large amount of data that you need to hold and manipulate inmemory, consider using the CBufSeg class. With HBufC and RBuf, the data is held asone contiguous memory cell within the heap; with a CBufSeg, it is held as individual cellslinked together. See the SDK for further details.100DESCRIPTORSHBufC DescriptorsAn HBufC can be created as follows:_LIT(KTxtHello, "Hello");HBufC* buffer = HBufC::NewL(32);*buffer = KTxtHello;delete buffer;This creates a memory cell on the heap with a maximum size of atleast 32 and then copies the string ‘Hello’ into it.7In C, the equivalent code would be:static char KTxtHelloWorld[] = "Hello";char* buffer = (char*)malloc(32);strcpy(buffer, KTxtHelloWorld);free buffer;The stack descriptors, TBuf and TBufC, are templated, and thetemplate value determines the length of the data area.

If you try to assigndata that is longer than the template value, the descriptor protects itselfby panicking. The HBufC descriptor is slightly different. It is allocated asa single cell from the heap (see Figure 5.8).HeapHBufC*0x02003D48Type 0Length 5HelloFigure 5.8 HBufC layoutTo save memory, it does not store its maximum length; instead, it findsout its maximum length by finding out the size of the heap cell it is storedin. Heap cells have a granularity that depends on the specific hardware to7For illustratative purposes this code is not as efficient as it could be, instead HBufC*buffer = KTxtHello().AllocL() could have been used; see the section on creatingan HBufC from another descriptor.HEAP DESCRIPTORS101which Symbian OS has been ported.

When allocating memory, SymbianOS always rounds up to the next nearest granularity boundary, so if youcreate an HBufC of a specific length, you may end up with a biggerdescriptor than you asked for. This becomes important in cases where,for example, you pass the descriptor to some method whose purpose isto return data in that descriptor. Do not assume that the length of datareturned in the descriptor is the same as the length you used to allocatethe descriptor.As you can see from the code fragment, you need a pointer to anHBufC type in your code; this can go onto the program stack or it canbe a data member of some class.

An HBufC is created via one of itsoverloaded NewL() or NewLC() methods, in a similar way to CBase-derived objects.The Des() methodYou can’t directly modify an HBufC type; however, you can use theDes() method to create a TPtr through which you can change theHBufC. An example is given in Section 5.5.There are some common misuses of the Des() method – see Section5.11).Creating an HBufC from another descriptorPrograms often need to create an HBufC from an existing descriptor.

Forexample, you might want to pass data into a method and then do someprocessing on that data. Typically you do not know the length of the databeing passed to your method, and so the easiest way to handle this is tocreate an HBufC descriptor within your method. We use the descriptormethod Alloc() or, more usually, one of its variants: AllocL() andAllocLC(). Here’s a simple example:_LIT(KTxtHelloWorld,"Hello World!");myFunctionL(KTxtHelloWorld);void myFunctionL(const TDesC& aBuffer){HBufC* myData = aBuffer.AllocLC();...}AllocL() (and the Alloc() and AllocLC() variants) creates anHBufC that is big enough to contain aBuffer’s data and then copiesthe data from aBuffer into myData. AllocL() does three jobs inone: it works out the length of the source descriptor, allocates the heapdescriptor, and then copies the data into the heap descriptor.102DESCRIPTORSChanging the size of an HBufCHeap descriptors can be created dynamically to whatever size is required.However, they are not automatically resized when additional storagespace is required, so you must ensure the buffer has sufficient memorybefore calling a modification operation.

If necessary, you can reallocatethe buffer to expand it to a new size using one of the ReAllocL()methods. This may change the location of the heap cell containing thedescriptor data in memory, so if there is a TPtr pointing to the HBufC itmust be reset (see Section 5.11).RBuf DescriptorsAn RBuf is similar to an HBufC in that it can be created dynamicallyand its data is stored on the heap.

However, as it derives from TDes,it has the benefit that it is directly modifiable, which means you do nothave to create a TPtr around the data in order to modify it. Thus RBufis preferable to HBufC when you know you need to dynamically allocatea descriptor and modify it.An RBuf can create its own buffer. Alternatively, it can take ownershipof a pre-allocated HBufC or a pre-allocated section of memory. Thememory must be freed by calling the Close() method.

Note that RBufdoes not automatically reallocate its memory cell if it needs to expand so,as with an HBufC, you still need to manage the memory for operationsthat may need the descriptor to expand.RBuf s are not named HBuf, because HBufC objects are directlyallocated on the heap (H stands for heap8 ); RBuf objects are not – theR prefix indicates that the class owns and manages its own memoryresources.

Unlike HBufC objects, RBuf objects can have their maximumlength set to the exact number you specify.Type 2Length5Maxlength50x02003D48Figure 5.9HelloRBuf (type 2) layoutThere are two types of RBuf object, as illustrated in Figures5.9 and 5.10, one that points to a memory area and one that pointsto an HBufC:_LIT(KTxtHello, "Hello");RBuf type2RBuf;type2RBuf.CreateL(5);8HBufC is not called CBufC, as it doesn’t inherit from CBase.

It is a notable exceptionto the Symbian OS naming convention for classes.HEAP DESCRIPTORS103type2RBuf = KTxtHello;type2RBuf.Close();HBufC* hBuf = KTxtHello().AllocLC();RBuf type4RBuf(hBuf);// assign ownership of hBuf to type4RBufCleanupStack::Pop(hBuf); // remove hBuf from the cleanup stacktype4RBuf.Close();// delete hBufType 4Length5Maxlength80x02003D48HeapType 0Length5HelloFigure 5.10 RBuf (type 4) layoutConstructionOn construction, an RBuf object can allocate its own buffer or takeownership of a pre-existing section of allocated memory or a pre-existingheap descriptor.For example, to construct an RBuf with a zero length, resizable bufferthat owns no allocated memory, use:RBuf myRBuf;To have an RBuf take ownership of an existing heap descriptor, use:HBufC* myHBufC = HBufC.NewL(20);RBuf myRBuf (myHBuf);In practice, your code may appear more along the lines of:RBuf resourceString (iEikEnv->AllocReadResourceL (someResourceId));104DESCRIPTORSNote that there’s no way to construct or set an RBuf from any arbitrarydescriptor type.

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

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

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

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