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

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

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

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

Only buffers that can explicitly be owned and releasedby the RBuf are supported. On construction, this is limited to HBufC,as others are ambiguous. Using the Assign() method discussed below,flat-heap-byte TUint arrays and existing RBufs are also supported:these are not supported through constructors, however, as the ownershiptransfer is not clear enough.CreationHaving constructed an RBuf that owns no data, data or space for datacan be associated with the RBuf using the Create() method. TheCreate() methods return a standard error code, usually KErrNone, ifsuccessful, or KErrNoMemory, if there is insufficient memory. For all theCreate() methods (including CreateMax()), there are correspondingCreateL() methods that leave on failure.To simply allocate space for data, without specifying the data itself, use:RBuf myRBuf;TInt maxSizeOfData = 20;if (myRBuf.Create(maxSizeOfData)) != KErrNone){...// error handling// Handling potential errors is omitted// from subsequent code examples for clarity.}The size of the descriptor data after running the above code is setto zero.

To set the size of the data to the maximum (i.e., equal to themaxSizeOfData parameter), use the CreateMax() method instead.It is also possible to create an RBuf with its data initialized. Forexample, to copy the contents of another descriptor into an RBuf, specifythe other descriptor as a parameter to the Create() or CreateL()method:RBuf myRBuf;TBufC<20> myTBufC (_L("Descriptor data"));myRBuf.CreateL(myTBufC);This sets the maximum size of the RBuf to the length of the sourcedescriptor. To specify a maximum size larger or smaller than this, passthe maximum size as the second parameter to the Create() method:RBuf myRBuf;_LIT(KGenesis, "In principio creavit Deus caelum et terram.");TInt maxSizeOfData = 30;myRBuf.CreateL(KGenesis(), maxSizeOfData); // trims text to 30// charactersHEAP DESCRIPTORS105A final option allows the contents of an RBuf’s data to be set froma stream which contains the length of the data followed by the dataitself.

Both the stream and the maximum permitted size of the streamare specified as parameters to the CreateL() method – there is noCreate() method available for setting an RBuf from a stream:RBuf myRBuf;RReadStream myStream;TInt maxSizeOfData = 30;myRBuf.CreateL(myStream, maxSizeOfData);Note that Create() orphans any data already owned by the RBuf,so Close() should be called where appropriate to avoid memory leaks.AssignmentAn RBuf can take ownership of a pre-allocated heap descriptor, use:HBufC* myHBufC = HBufC::NewL(20);RBuf myRBuf.Assign(myHBufC);To transfer ownership of another RBuf, the RBuf is specified as theparameter to the Assign() method:RBuf myRBuf1;RBuf myRBuf2;HBufC* myHBufC = HBufC::NewL(20);myRBuf1.Assign(myHBufC); // take ownership of heap memorymyRBuf2.Assign(myRBuf1); // take ownership of another RBufmyRBuf2.Close();Finally, the RBuf can take ownership of pre-allocated memory on theheap by specifying the heap cell and the maximum size of the data:TInt maxSizeOfData = 20;RBuf myRBuf;TUint16* pointer = static_cast<TUint16*>(User::AllocL (maxSizeOfData*2));myRBuf.Assign(pointer, maxSizeOfData);For this call, the current size of the descriptor is set to zero.

To specifya different size, insert this value as the second parameter. As an example,the last line of the code snippet above could be replaced by:TInt currentSizeOfData = maxSizeOfData / 2;myRBuf.Assign(pointer, currentSizeOfData, maxSizeOfData);106DESCRIPTORSNote that Assign() orphans any data already owned by the RBuf,so Close() should be called where appropriate to avoid memory leaks.The Swap() method allows the contents of two RBufs to be exchanged.ReallocationHaving created an RBuf, the data space in the descriptor can be resizedif the data should exceed the size of the descriptor.

This is achieved byusing the ReAlloc() method:myRBuf.CleanupClosePushL();...const TInt newLength = myRBuf.Length() + appendBuf.Length();if (myRBuf.MaxLength() < newLength){myRBuf.ReAlloc(newLength);}myRBuf.Append(appendBuf);...CleanupStack::PopAndDestroy();// calls myRBuf.Close();If the ReAlloc() method is used on an HBufC object, the change inlocation of the heap cell means that any associated HBufC* and TPtrvariables need to be updated.

This update isn’t required for RBuf objects.A corresponding ReAllocL() method is available that acts similarlybut leaves on failure.DestructionRegardless of the way in which the buffer has been allocated, theRBuf object is responsible for freeing memory when the object itself isclosed. Both the Close() and the CleanupClosePushL() methodsare available and should be called appropriately. See the example forReAlloc() above.Other methodsWe have discussed the methods introduced in the RBuf class. Since RBufinherits from TDes, all the methods from TDes and TDesC are availableto RBuf and can be used as described in the Symbian Developer Librarydocumentation._LIT(KTextHello, "Hello");_LIT(KTextWorld, " World");RBuf myRBuf;myRBuf.CleanupClosePushL();myRBuf.CreateL(KHello());HEAP DESCRIPTORS107imyRBuf.ReAllocL(KHello().Length() + KWorld().Length());myRBuf.Append(KWorld);CleanupStack::PopAndDestroy() // calls myRBuf.Close();Migration from HBufCIt is desirable to migrate code that uses HBufC* and TPtr so that it usesjust RBuf.• It makes the code easier to read and understand and hence to maintain.• It reduces the possibility of errors.• The object code is slightly smaller as a TPtr doesn’t have to becreated around the object in order to modify it, as it does with anHBufC.Since it is possible to create an RBuf from an existing HBufC, it’seasy to move code over to this new class.

For example, when Symbianwas migrating code internally, the changes were mainly from code of theform:HBufC* mySocketName;...if(mySocketName==NULL){mySocketName = HBufC::NewL(KMaxName);}TPtr socketNamePtr (mySocketName->Des());aMessage.ReadL(aMessage.Ptr0(), socketNamePtr);// where aMessage is of type RMessage2to code like this:RBuf mySocketName;...if(mySocketName.IsNull()){mySocketName.CreateL(KMaxName);}aMessage.ReadL(aMessage.Ptr0(), mySocketName);An RBuf can directly replace an HBufC, so you can use it to callpredefined APIs that return HBufC s.

For example:HBufC* resString = iEikonEnv->AllocReadResourceLC (someResourceId);// increase size of label, copy old text and append new textlabelLength += 4;108DESCRIPTORSHBufC* label = HBufC::NewLC(labelLength);TPtr labelPtr(label->Des());labelPtr.Copy(*resString);labelPtr.Append(_L("-Foo"));//.

. . etc.SetLabelL(ELabel, *label);CleanupStack::PopAndDestroy(2);converts to:RBuf resString (iEikonEnv->AllocReadResourceL(someResourceId));resString.CleanupClosePushL();// Use modifiable descriptor to append new text. . .resString.ReAllocL(resString.Length() + 4);resString.Append(_L("-Foo"));//. . . etc.SetLabelL(ELabel, resString);CleanupStack::PopAndDestroy() // calls resString.Close();5.7 Narrow, Wide and Neutral DescriptorsSo far the descriptors we have seen are known as neutral descriptors.They are neutral in that their class names do not indicate if they storewide or narrow data.

There are actually two sets of descriptor classes: aset of narrow classes for storing 8-bit data and a set of wide classes forstoring 16-bit data. Their names end in either 8 or 16 to explicitly indicatewhat type of data they store, narrow or wide.If you specifically need to use narrow or wide data, you can usethe narrow or wide descriptor classes directly instead of the neutraldescriptors.So are the neutral descriptors wide or narrow? The answer is that theymay be either depending upon a compile-time flag. If you look in thee32std.h header file, you’ll be able to see the typedef s and the buildflag, the _UNICODE macro. Here is how it is done for TDesC and TBufC:#if defined(_UNICODE)typedef TDesC16 TDesC;#elsetypedef TDesC8 TDesC;#endiftemplate <TInt S>#ifdef _UNICODEclass TBufC : public TBufCBase16#elseclass TBufC : public TBufCBase8#endifHere is a list of the neutral, narrow and wide classes involved in thisscheme.DESCRIPTORS AND BINARY DATANeutralNarrowWide_LITTDesCTDesTPtrCTPtrTBufCTBufHBufCRBuf_LIT8TDesC8TDes8TPtrC8TPtr8TBufC8TBuf8HBufC8RBuf8_LIT16TDesC16TDes16TPtrC16TPtr16TBufC16TBuf16HBufC16RBuf16109You can find these definitions in e32def.h, e32std.h, e32des8.hand e32des16.h.Symbian OS was designed from the beginning to support worldwidelocales and although early versions used narrow 8-bit characters, itsarchitects planned for 16-bit characters from the beginning.

It was decidedto concentrate effort first on developing Symbian OS with narrow stringsand in the future it would be changed to deal with wide strings. Thetechnical foundation of the Symbian OS strategy was to program using theneutral versions of descriptors, then by simply changing the compilationflag, it would be possible to rebuild Symbian OS with 16-bit or 8-bitcharacters.Early versions of Symbian OS, up to and including v5.0, used narrowcharacters. The next version, v5.0U (the U stands for Unicode) andsubsequent versions used wide characters.

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

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

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

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