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

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

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

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

It also traps leaves that occur in your test code. Youmust always use the cleanup stack from within a TRAP, which is why theseparate function, RunConsoleL(), has been defined. If you don’t havea TRAP and attempt to use the cleanup stack, your code will panic withE32USER-CBASE 69.UHEAP MARK andUHEAP MARKEND are useful macros thatdetect memory leaks on the heap. WhenUHEAP MARK is called,the heap level (i.e., the amount of heap used at the time) is internallyrecorded. Then, when UHEAP MARKEND is called, if the current heaplevel does not match (i.e., there are allocations on the heap that were notthere whenUHEAP MARK was called), an ALLOC panic is generated.We used them in the above code so that you can see if any of the testcode you entered did not properly free up allocated memory.

Note thatthese macros are only used in debug builds and are ignored otherwise.They are useful for catching memory leaks.The MMP file for the console project is shown below.TARGETTARGETTYPEUIDSOURCEPATHSOURCEUSERINCLUDESYSTEMINCLUDELIBRARYtests.exeexe0.tests.cpp.\Epoc32\includeeuser.libTo compile this console program, use the following commands (youonly need to issue the bldmake command once to set up the makefiles):bldmake BLDFILESabld build winscwudeb164STRINGS, BUFFERS, AND DATA COLLECTIONSNote that the MMP file defined here is only suitable to run the consoleprogram on the emulator, which is all that’s needed for the examplesin this chapter. You can, however, also run a console program onthe device, but you would need to define a reg.rss resource fileand specify it in a resource section of your MMP (resource sectionsare discussed in section 5.3.2, registration resources are discussed inChapter 12).Figure 6.1 Console Output on the S60 3rd Edition FP1 EmulatorThe abld build command shown builds a windows executablecalled tests.exe in the <SDK Installation Directory>\epoc32\release\winscw\udeb directory.

If you run this executable, it bringsup the emulator and immediately runs your console app. Figure 6.1shows the output for tests.exe built with the code and MMP fileshown above. To simplify running, you can create a batch file in thesame directory as the source file, which executes the EXE in the releasedirectory (so you do not have to change to that directory).DESCRIPTORS FOR STRINGS AND BINARY DATA165Now, let’s get on with our discussion of strings and buffer management, starting with the most commonly used Symbian OS data classes:descriptors.6.2 Descriptors for Strings and Binary DataDescriptors are classes that represent data buffers and allow you tosafely access them. Symbian OS uses descriptors to store and manipulatestrings (as opposed to NULL-terminated C strings), as well as to managebinary data.

Descriptor classes, although containing many features, areoptimized for minimal overhead, since they are designed to run onmemory-constrained devices.You’ll need to thoroughly understand descriptors in order to developSymbian OS code, since they are so widely used. In fact, you’ll need to usethem just to call many of the Symbian OS API functions, since descriptorsare often passed to them as arguments. Descriptors are powerful, butsince their use is so unique when compared with other operating systems,they can be a source of some initial confusion to programmers startingout in Symbian OS.A descriptor class encapsulates a data buffer as well as the buffer’ssize – the size being used to prevent buffer overruns.

There are multipledescriptor classes you will need to be familiar with – these classes differin how the data buffer is stored and referenced, as well as the width ofthe buffer’s data and whether the buffer is modifiable or not. Descriptorclasses also contain numerous methods that allow you to read and writethe buffers as well as transform the data, using an interface consistentacross the different descriptor types.6.2.1 Strings versus Binary DataBoth strings and binary data buffers are treated as data buffers of aspecific length.

Of course, if your descriptor contains binary data, thenthe string manipulation methods of the descriptor (e.g., LowerCase())are not applicable. Another difference is that strings are usually stored in16-bit descriptors while binary data is stored in 8-bit descriptors. This isbecause Symbian OS uses Unicode and thus deals with 16-bit characters.For binary data, however, 8-bit descriptors are normally used, since thebinary data is treated as simply a buffer of bytes.6.2.2 Preventing Memory OverrunsA memory overrun occurs when your software writes past the end of anallocated buffer.

The worst thing about a memory overrun is that it will166STRINGS, BUFFERS, AND DATA COLLECTIONSoften go unnoticed at first and then manifest itself later as an intermittentcrash – often in functions far removed from where the overrun occurred.As a result, a memory overrun can be extremely hard to debug and theyalways seem to occur close to – or after – product release.A big advantage of a descriptor is that it prevents data from beingwritten outside of the allocated buffer.

When an access is attemptedbeyond the buffer limit, the descriptor raises a panic when the actualoverrun occurs, making it significantly easier to find and fix the problem.However, nothing will prevent a memory-overrun attempt, so you needto avoid such attempts and test vigorously to avoid having panics in yourproduction code.6.2.3 Simple Descriptor ExampleBefore describing the descriptor classes in detail, let’s look at a simplestring example – comparing its implementation both in C and in SymbianOS using descriptors.The example implements a function called MakeName(), which concatenates the string passed as its argument to the string literal "Name:",and prints the results.

Note that the goal of this example is just to introducea few C string and descriptor differences and not to show the best way toimplement the actual functionality of the example.First, let’s look at the example, written using C strings:char *namePrefix="Name:";void MakeName(char *aName){char str[80];strcpy(str,namePrefix);strcat(str,aName);printf("str= %s ",str);}void MainFunc(){MakeName("Sharon");}In C, strings are represented as a set of characters terminated by aNULL. The literal namePrefix is declared as a char* and assignedthe string "Name:" – a literal stored in the code image.

MakeName()accepts its string argument as a char*. It declares a temporary stringbuffer as an array of char’s and then uses strcpy() and strcat() tocopy the name prefix and append the name passed to the function intothe temporary string. When the code invokes MakeName(), it passes itsstring argument as a quoted string.DESCRIPTORS FOR STRINGS AND BINARY DATA167Now let’s look at the same example rewritten to use descriptors:_LIT(KNamePrefix,"Name:");void MakeName(const TDesC& aName){TBuf<80> str;str.Copy(KNamePrefix);str.Append(aName);console->Printf(_L("str = %S\n"),&str);}void MainFunc(){MakeName(_L("Sharon"));}The first thing to note is how string literals are declared.

In Symbian OS,string literals are declared as descriptors using either the LIT macro orthe L macro.The prefix string literal is declared as:_LIT(KNamePrefix, "Name: ");The LIT macro is called to take the string "Name: " and storesboth the string (no NULL) and the string’s size in the descriptor literalKNamePrefix.Notice also that the example invokes MakeName() as follows:makeName(_L("Sharon"));The L macro is like LIT except that this one does not assign anintermediate constant as LIT does. I discuss other differences betweenthese macros in section 6.3.2.MakeName() accepts its string argument as a descriptor instead of achar *:void MakeName(TDesC &aName)There are several different types of descriptor classes (see section 6.3), andTDesC is the base class of all descriptors – thus, declaring the argumentin this way ensures that the function will accept any type of descriptor.In the C example, the temporary string in MakeName() was declaredas an array of 80 characters as follows:char str[80];168STRINGS, BUFFERS, AND DATA COLLECTIONSIn Symbian OS, str is declared as a descriptor instead:TBuf<80> str;TBuf is a 16-bit modifiable descriptor class with a maximum size(specified as the template parameter) of 80 characters.

Like an array,TBuf stores the string buffer on the stack.The example then builds the final string into the temporary descriptorby copying the name prefix into the temporary descriptor and appendingthe passed name as follows:str.Copy(KNamePrefix);str.Append(aName);The Copy() and Append() descriptor methods are the counterparts toC’s strcpy() and strcat() functions. Copy() here copies the specified descriptor data KNamePrefix to str’s descriptor buffer, replacinganything that’s there. Append() appends the descriptor string data inaName to str’s buffer.If the name passed into MakeName() was large enough such thatstr exceeded 80 characters, the C version of the code would overrunits buffer.

However, the descriptor version will immediately panic if thestring exceeds 80 characters, since the Copy() and Append() methodsknow that the size allocated to the descriptor is 80 characters.Note that it would have been easier in the C example to create the stringin MakeName() by using sprintf(str, "%s %s",namePrefix,name) instead of doing a string copy on the prefix and concatenating the name (the goal was just to show those string functions).

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

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

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

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