Главная » Просмотр файлов » Symbian OS Explained - Effective C++ Programming For Smartphones (2005)

Symbian OS Explained - Effective C++ Programming For Smartphones (2005) (779885), страница 48

Файл №779885 Symbian OS Explained - Effective C++ Programming For Smartphones (2005) (Symbian Books) 48 страницаSymbian OS Explained - Effective C++ Programming For Smartphones (2005) (779885) страница 482018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

If a second copyof the EXE is launched, the program code and read-only static data areais shared, and only a new area of read/write data is allocated.13.2Symbian OS DLLsDynamic link libraries, DLLs, consist of a library of compiled C++ codethat may be loaded into a running process in the context of an existingthread. On Symbian OS there are two main types of DLL: shared libraryDLLs and polymorphic DLLs.A shared library DLL implements library code that may be usedby multiple components of any type, that is, other libraries or EXEs.The filename extension of a shared library is .dll – examples of thistype are the base user library (EUser.dll) and the filesystem library(EFile.dll). A shared library exports API functions according to amodule definition (.def) file. It may have any number of exportedfunctions, each of which is an entry point into the DLL.

It releases aheader file (.h) for other components to compile against, and an importlibrary (.lib) to link against in order to resolve the exported functions.When executable code that uses the library runs, the Symbian OS loaderloads any shared DLLs that it links to and loads any further DLLs thatthose DLLs require, doing this recursively until all shared code neededby the executable is loaded.The second type of DLL, a polymorphic DLL, implements an abstractinterface which is often defined separately, for example by a framework.It may have a .dll filename extension, but it often uses the extensionto identify the nature of the DLL further: for example, the extension.app identifies an application, .fep a front-end processor and .mdla recognizer.

Polymorphic DLLs have a single entry point ”gate” or”factory” function, exported at ordinal 1, which instantiates the concreteclass that implements the interface. The interface functions are virtual;they are not exported and are instead accessed by the virtual functiontable, through a pointer to the base class interface. Polymorphic DLLsare often used to provide a range of different implementations of a singleconsistent interface, and are loaded dynamically at run-time by a call toRLibrary::Load().This type of DLL is often known as a ”plug-in” – recognizers area good example of plug-ins. The component that determines whichplug-ins to load, instantiate and use is typically known as a framework.

The framework which loads the recognizers is provided by theapplication architecture server (Apparc). It can load any number of recognizer plug-in DLLs, which examine the data in a file or buffer and, ifthey ”recognize” it, return its data (MIME) type. Each recognizer plug-inexports a function at ordinal 1 that constructs and returns an instanceof the CApaDataRecognizerType interface. The plug-in must provideSYMBIAN OS DLLs219a concrete class which implements the three pure virtual functionsof the interface: DoRecognizeL(), SupportedDataTypeL() andPreferredBufSize().Recognizer plug-in DLLs are identified by having UID1 set toKDynamicLibraryUid (0x10000079), UID2 set to KUidRecognizer(0x10003A19) and UID3 set to a unique value to identify each individual implementation.

Each recognizer has a .mdl file extension and itstargettype should be MDL. Don’t worry too much about this rightnow though – UIDs and the targettype specifier are described later inthe chapter.Up until Symbian OS v7.0, each framework that could be extendeddynamically by plug-in code was required to take responsibility for findingthe appropriate plug-ins, loading and unloading them, and calling theentry point functions to instantiate the concrete interface implementation.The ECOM framework was introduced in Symbian OS v7.0 to providea generic means of loading plug-in code, simplifying the use of plug-insand reducing code duplication. I’ll discuss ECOM further in Chapter 14.Apparc implemented its own custom loading of recognizer plug-ins up tov8.0; in this latest release it has been modified to use ECOM.For both types of DLL, static and polymorphic, the code section isshared.

This means that, if multiple threads or processes use a DLLsimultaneously, the same copy of program code is accessed at the samelocation in memory. Subsequently loaded processes or libraries that wishto use it are ”fixed up” to use that copy by the DLL loader.DLLs in ROM are not actually loaded into memory, but execute inplace in ROM at their fixed address. DLLs running from RAM are loadedat a particular address and reference counted so they are unloaded onlywhen no longer being used by any component. When a DLL runs fromRAM,1 the address at which the executable code is located is determinedonly at load time. The relocation information to navigate the code of theDLL must be retained for use in RAM. However, DLLs that execute fromROM are already fixed at an address and do not need to be relocated.Thus, to compact the DLL in order to occupy less ROM space, SymbianOS tools strip the relocation information out when a ROM is built.

Thisdoes mean, however, that you cannot copy a DLL from the ROM, store itin RAM and run it from there.On Symbian OS, the size of DLL program code is further optimized tosave ROM and RAM space. In most operating systems, to load a dynamiclibrary, the entry points of a DLL can either be identified by stringmatching their name (lookup by name) or by the order in which they areexported (lookup by ordinal). Symbian OS does not offer lookup by namebecause this adds an overhead to the size of the DLL (storing the names of1Loading a DLL from RAM is different from simply storing it on the internal (RAM) drive,because Symbian OS copies it into the area of RAM reserved for program code and preparesit for execution by fixing up the relocation information.220BINARY TYPESall the functions exported from the library is wasteful of space).

Instead,Symbian OS only uses link by ordinal, which has significant implicationsfor binary compatibility. Ordinals must not be changed between onerelease of a DLL and another, otherwise code which originally used theold DLL will not be able to locate the functions it needs in the newversion of the DLL. I’ll discuss binary compatibility further in Chapter 18.13.3Writable Static DataWhile EXE components have separate data areas for program code,read-only data and writable data, DLLs do not have the latter. This hasthe following consequence: Symbian OS DLLs do not support writableglobal data.So why is there no writable data section for Symbian DLLs? The reasonis that any code which refers to global data must use an address to doso, rather than an offset from a pointer.

When code is loaded, it musteither use a fixed address to somewhere in the DLL in order to locate thedata, or it must use a relocation value for the data, if it is moved to a newaddress. Furthermore, because DLLs are shared between processes, everyprocess in which it loads must use the same address for the global data.2Thus, each DLL that supported writable static data would need asection of RAM (a ”chunk”, the basic unit of system memory) allocatedfor it within every process that loaded it, just for static data.

The smallestsize of a chunk is 4 KB – which comes to a significant overhead whenyou consider the number of DLLs that a typical application on SymbianOS might use (often over 50), and the fact that the DLL would typicallywaste most of this memory, since it is unlikely to declare exactly 4 KBworth of static data.This restriction means that you cannot use static member variables,such as those used to implement the singleton pattern (which allowsonly one instance of a class to be instantiated and used, and is useful forimplementing a single ”controller” type object). This can be inconvenient,particularly when porting code which makes uses of this idiom, or indeedany other which requires global data.Here’s an example of a simple task manager where I’ve included justthe minimum amount of code needed to illustrate the use of a singleton.// TaskManager.h // Header fileclass CTask; // Defined elsewhere2If the required address for the data has already been occupied when a DLL comes toload, the DLL will not be usable.

This is quite possible, because the data is placed in achunk which means that its address must start on a megabyte boundary, of which there arefew. A workaround would be to copy the program code for the DLL, and adjust the copy touse a different address for the static data, but the overhead would be unacceptably high.WRITABLE STATIC DATAclass CTaskManager : public CBase{public:IMPORT_C static CTaskManager* TaskManagerL();IMPORT_C static void DestroyTaskManager();public:IMPORT_C void AddTaskL(CTask* aTask);//... Omitted for clarityprivate:CTaskManager();// Private - destroy the singleton through DestroyTaskManager()∼CTaskManager();void ConstructL();private:CTaskManager(const CTaskManager&);// Not implementedCTaskManager& operator =(const CTaskManager&);// Prevents copyingprivate:static CTaskManager* iTaskManager;// The singleton instanceprivate:RPointerArray<CTask>* iTasks;...};// TaskManager.cpp // Implementation// Initializes the static dataCTaskManager* CTaskManager::iTaskManager = NULL;EXPORT_C CTaskManager* CTaskManager::TaskManagerL(){if (!iTaskManager){// Construct the singleton object on first useCTaskManager* taskManager = new (ELeave) CTaskManager();CleanupStack::PushL(taskManager);taskManager->ConstructL();CleanupStack::Pop(taskManager);iTaskManager = iTaskManager;}return (iTaskManager);}EXPORT_C void CTaskManager::DestroyTaskManager(){delete iTaskManager;iTaskManager = NULL;}// The use of dynamic arrays is discussed in Chapter 7void CTaskManager::ConstructL(){// Creates the underlying arrayiTasks = new (ELeave) RPointerArray<CTask>(4);}// Exported function through which clients manipulate the arrayEXPORT_C void CTaskManager::AddTaskL(CTask* aTask){User::LeaveIfError(iTasks->Append(aTask));}221222BINARY TYPESCTaskManager::∼CTaskManager(){if (iTasks){iTasks->Close();delete iTasks;}}The implementation works well in an EXE component, but because ofits use of writable static data cannot be used in a DLL.

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

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

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

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