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

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

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

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

Although the 16-bit descriptorsare called ‘Unicode’, they are in fact UTF-16, which is an encoding ofUnicode.Today, Symbian OS is always built using 16-bit wide characters butit is conventional to use the neutral classes unless there is an instancewhere you need to explicitly use a narrow or wide descriptor. Code allyour general-purpose text objects to use the neutral variants.

Where youare using descriptors to refer to binary data, code specifically using 8-bitclasses, for example, TDesC8.5.8 Descriptors and Binary DataYou can use descriptors to store and manipulate binary data just as youcan string data. The main reason you can do this is because descriptorsinclude an explicit length, rather than using NULL as a terminator.The data APIs and string APIs offered by descriptors are almostidentical.110DESCRIPTORS• Use TDesC8, TDes8, TBuf8, TPtr8, etc. rather than their equivalentTDesC, TDes, TBuf and TPtr character classes.• Use TUint8 or TInt8 for bytes, rather than TText.• Locale-sensitive character-related methods, such as FindF() andCompareF(), aren’t useful for binary data.• You can use Size() to get the number of bytes in a descriptor,whether it’s an 8-bit or 16-bit type.APIs for writing and reading, or sending and receiving, are oftenspecified in terms of binary data.

Here, for example, is part of the RFileAPI:class RFile : public RFsBase{public:IMPORT_C TInt Open(RFs& aFs, const TDesC& aName, TUint aFileMode);IMPORT_C TInt Create(RFs& aFs, const TDesC& aName, TUint aFileMode);IMPORT_C TInt Replace(RFs& aFs, const TDesC& aName, TUint aFileMode);IMPORT_C TInt Temp(RFs& aFs, const TDesC& aPath,TFileName& aName, TUint aFileMode);IMPORT_C TInt Write(const TDesC8& aDes);IMPORT_C TInt Write(const TDesC8& aDes, TInt aLength);IMPORT_C TInt Read(TDes8& aDes) const;IMPORT_C TInt Read(TDes8& aDes, TInt aLength) const;...};The Open(), Create(), Replace() and Temp() methods take afilename, which is text, and is specified as a const TDesC&.The Write() methods take a descriptor containing binary data to bewritten to the file.

For binary data, these classes are specified as constTDesC8&, the ‘8’ indicating that 8-bit bytes are intended, regardlessof the size of a character. The version of Write() that takes only adescriptor writes its entire contents (up to Length() bytes) to the file.Many APIs use descriptors exactly like this, for sending binary data toanother object.5.9 Using Descriptors with MethodsThis section describes the most appropriate types to use when passingdescriptors to, and returning them from, methods.Descriptors as ParametersThe following guidelines should be followed when using descriptors asmethod parameters:USING DESCRIPTORS WITH METHODS111• To pass a descriptor as an input parameter into a method (i.e., to passdescriptor data that is read within the method but is not changed), useconst TDesC& as the parameter type.• To pass an in–out parameter to a method (i.e., to pass descriptordata that you want to change within your method), use TDes& as theparameter type.The following global method, appendText(), is an example of theuse of const TDesC& and TDes& parameters:void appendText(TDes& aTarget, const TDesC& aSource){aTarget.Append(aSource);}_LIT(KTxtHello, "Hello");_LIT(KTxtWorld, " World!");TBuf<12> helloWorld(KTxtHello);appendText(helloWorld, KTxtWorld);When the call to appendText() returns, helloWorld contains thetext ‘Hello World!’.The important point to note with this example is that any descriptortype can be passed as the aSource parameter.

If we had prototyped themethod in such a way that aSource was, for example, of type TBuf orTPtr&, then we would need to add variants of the method to cope withall possible permutations, which is clearly wasteful.While any descriptor type can be passed into a method taking constTDesC&, only TPtr, TBuf or RBuf can be passed into methods takingTDes&.The next example shows first how an RBuf can be passed to theappendText() method and then how an HBufC can be passed toappend itself to itself. Note that as an HBufC cannot be passed as aTDes& parameter, a TPtr to the data in the HBufC must be passedinstead:TInt maxLen = KTxtHello().Length() + KTxtWorld().Length();RBuf helloBuf;RBuf worldBuf;helloBuf.CreateL(KTxtHello, maxLen);helloBuf.CleanupClosePushL();worldBuf.CreateL(KTxtWorld);// "Hello"appendText(helloBuf, worldBuf);// "Hello World!"CleanupStack::PopAndDestroy(&helloBuf);worldBuf.Close();HBufC* heapBuf = HBufC::NewL(maxLen);heapBuf->Des() = KTxtHello();// heapBuf contains "Hello"112DESCRIPTORSappendText(heapBuf->Des(), *heapBuf);// heapBuf now contains "HelloHello"delete heapBuf;An empty descriptor can be passed to a method expecting a constTDesC& using the KNullDesC literal.

There are also KNullDesC8 andKNullDesC16 variants. All three define an empty or null descriptorliteral (in e32std.h):_LIT(KNullDesC,"");_LIT8(KNullDesC8,"");_LIT16(KNullDesC16,"");When declaring method parameters you must declare TDesC andTDes as pass by reference and not by value and you should also not omitconst when using TDesC – see Section 5.11.Generally, method parameters should be either const TDesC& orTDes& but there may be occasions when you need to use other types.Using RBuf& as a method parameterIf you need to create a heap buffer within your method and pass ownershipto the calling code, then the choice is between an HBufC and an RBuf.The standard pattern for creating an HBufC is to return it from the methodas described in Section 5.9, however this is not possible for an RBuf (asits copy constructor is protected); instead, it may be achieved as follows:void FooL(RBuf& aBuf){aBuf.CreateL(KMaxLength); // potential memory leak// fill with data}RBuf buf;FooL(buf);However calling CreateL() twice causes a memory leak.

In theabove code, if the RBuf has already been created, a leak results. Analternative therefore is to call ReAllocL(); note how this works in bothsituations below:void copyTextL(RBuf& aDes){_LIT(KTxtHello, "Hello");if (aDes.MaxLength() < KTxtHello().Length()){aDes.ReAllocL(KTxtHello().Length());USING DESCRIPTORS WITH METHODS113}aDes = KTxtHello;}RBuf rBuf1;FooL(rBuf1);rBuf1.Close();RBuf rBuf2;rBuf2.CreateL(3);rBuf2.CleanupClosePushL();FooL(rBuf2);CleanupStack::PopAndDestroy();RBuf::ReAllocL() does not suffer from the same potential problems as HBufC::ReAllocL(), described in Section 5.11.Using TPtrC& as a method parameterTPtrC is frequently used as a return type from a method, however theremay be occasions when the method return is being used for somethingelse and it is necessary to use the TPtrC as a parameter instead:_LIT(KTxtHelloWorld, "Hello World!");TInt CSomeClass::GetWorld(TPtrC& aWorldOut){iBuf = KTextHelloWorld;// iBuf may be a TBufC<x>aWorldOut.Set(iBuf.Mid(6,5));return KErrNone;}CSomeClass* someClass = CSomeClass::NewL();TPtrC ptr;TInt ret = someClass->GetWorld(ptr);// ptr contains "World"delete someClass;Note that TPtrC and const TPtrC& are not used as method parameters.Using const TDesC* as a method parameterThere may be occasions when a descriptor parameter can have a NULLinput, that is when no descriptor object is passed (as opposed to whenan empty descriptor is passed).

In these circumstances, const TDesC*could be used:class TSomeClass{public:void Foo(const TDesC* aDes = NULL);};114DESCRIPTORS...someClass.Foo(&someDescriptor.Left(x)); // be wary!However if you do this, you should be wary of calling the methodwith a temporary object as C++ does not guarantee what the behavior iswhen passing a temporary object by const*. Instead you could consideroverloading the method in combination with using inlines:class TSomeClass{public:inline void Foo();inline void Foo(const TDesC& aDes);private:void DoFoo(const TDesC* aDes);};inline void TSomeClass::Foo(){ DoFoo(NULL); }inline void TSomeClass::Foo(const TDesC& aDes){ DoFoo(&aDes); }Using HBufC*& as a method parameterUsually, if a method needs to create an HBufC and pass ownershipof it to the caller this is done by returning it, however there may becircumstances when something else must be returned from the method.In these circumstances, this can be accomplished using a parameterinstead:TInt FooL(HBufC*& aBuf){ASSERT(aBuf == NULL);aBuf = KTxtHelloWorld().AllocL();return KErrNone;}HBufC* buf = NULL;FooL(buf);delete buf;Note that if the HBufC needs to be created before being passedto a method and assigned within the method, then this can also beaccomplished using an HBufC*& parameter, though if you need to useReAlloc() within the method, then caution should be exercised (seeSection 5.11).Returning Descriptors from MethodsWhich descriptor type to use as a return from a method depends upon:• whether a descriptor or raw data is being returnedUSING DESCRIPTORS WITH METHODS115• whether the entire part, or just a portion, of the descriptor or raw datais being returned• whether the descriptor or raw data being returned is constant ormodifiable• whether a heap descriptor is being created within the method andownership is to be transferred to the caller.Returning an entire constant descriptorIf you are returning an entire descriptor that exists while the caller of themethod uses it and the descriptor is not to be modified, then you shouldreturn const TDesC&:const TDesC& CSomeClass::ReturnConstantEntireDescriptor() const{return iDescriptor;}CSomeClass* someClass = CSomeClass::NewL();TPtrC p = someClass->ReturnConstantEntireDescriptor();// use pdelete someClass;Returning a partial constant descriptorIf you are returning part of a descriptor that exists while the caller of themethod uses it and the descriptor is not to be modified, then you shouldreturn TPtrC:TPtrC CSomeClass::ReturnConstantPartialDescriptor() const{return iDescriptor.Right(4); // return the rightmost 4 chars}TPtrC p = someClass->ReturnConstantPartialDescriptor();// use pA TPtrC occupies 8 bytes, which means it is officially allowed tobe passed to and returned from methods by value (as opposed to byreference) according to the Symbian OS coding standards.In this example, return iDescriptor.Right(4) creates andreturns a temporary TPtr object, however it is safe to do so as themethod return type is a TPtrC; it is returning by value and not by reference.

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

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

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

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