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

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

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

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

Both outputs are placed in the build platform’s releasedirectory (e.g., epoc32\release\gcce\urel). The emulator can loadand use the DLL directly from that directory. On the target phone, DLLsshould be placed in the \sys\bin directory.Programs that use the DLL need to statically link to the import library.Adding the DLL’s import library name to the LIBRARY statement in theprogram’s MMP file will allow this.

The program will then access the DLLfunctions through this import library.Figure 5.2 shows the relationship between the import library and theshared library.The DLL’s import functions (simple wrappers whose only job is toinvoke the actual code contained in the DLL) reside in the DLL user’sexecutable since the import library is statically linked.

To illustrate this,executing a library function called MyDllFunc1() first invokes it in theimport library, which then locates and invokes it in the DLL. The importlibrary will also load the DLL if necessary.Note that although I specified the import library with a suffix of .libin the figure, the library could have a .dso depending on the build target,as discussed in section 5.4.2.5.7.2 Referencing Functions by OrdinalTo understand the discussions that follow, you need to understandhow functions within an import library invoke their DLL functioncounterparts.As you saw in Chapter 4, EXPORT C and IMPORT C are used toindicate which functions in a DLL are exported (i.e., available for outsideuse).

When the DLL is built, each exported function is assigned a uniqueinteger value known as an ordinal. DLL functions are invoked at runtimeusing these ordinal values. To illustrate this, suppose that MyDllFunc1()is assigned an ordinal of 5 when the DLL is built. The import library’sMyDllFunc1() will invoke the corresponding MyDllFunc1() functionin the DLL by looking up function number 5 in that DLL (by usingRLibrary class’s Lookup() method described in the next section) andexecuting it.The import library and the DLL ordinal numbers must line up. Imaginethe trouble you will have if you update your DLL, and rebuild it suchthat MyDllFunc1() has a different ordinal value.

If applications linkedwith the older import library are run – and the MyDllFunc1() importfunction is called – the wrong function in the DLL will be invoked (i.e.,whatever function is now at ordinal 5). This wrong function call couldcause a software crash or other error that could be very hard to debug.This situation is exactly what the interface-freezing feature of SymbianOS is meant to prevent, as you will see.1445.7.3SYMBIAN OS BUILD ENVIRONMENTRLibrary API ClassSymbian OS provides an API class called RLibrary to load and invokeDLL functions dynamically at runtime.

The import library uses this API toaccess the DLL and so it’s instructive to have a quick look at this class,even though the import library shields you from needing to use it.The key methods of RLibrary are Load() and Lookup(). TheLoad() method is used to load a specific DLL and associate it withthe class. The Lookup() method will look up the DLL function withthe ordinal value passed to it.The following is a simple example of using RLibrary. It loads a DLLcalled MyDll.dll and calls the DLL function whose ordinal value is 1:RLibrary lib;lib.Load(_L("MyDll.dll"));TLibraryFunction MyFirstFunc=library.Lookup(1);MyFirstFunc();lib.Close();In addition to its use by system code to access import libraries, anapplication can make explicit use of the RLibrary class. Explicit useis necessary when using DLLs that act as plug-ins, such as polymorphicDLLs.

See Chapter 4 for more information.5.8 DLL Interface FreezingDLL freezing is a mechanism to ensure that newly released DLLs willremain backward compatible with previously released versions of theDLL’s import libraries. It works by ensuring that the function ordinalscurrently available in a released import library correspond with theordinals used by future versions of the DLL, even when new functions areadded.DLL freezing is only applicable if you are developing a shared libraryDLL, so if you do not plan on doing this you can skip this section.

Also, aswith the rest of this chapter, this section focuses on using the commandline tools. However, I want to point out that with Carbide.c++, interfacefreezing is performed by simply selecting the ‘Freeze exports’ option inthe project menu. Even if you are developing your DLL with Carbide.c++though, this section is useful to understand what freezing is and why it’sneeded, although you could skip the command line explanation.Why is DLL freezing important?Imagine that you are developing a DLL that will be released for widespreaduse.

On initial shipment, you release the DLL itself and a correspondingDLL INTERFACE FREEZING145import library. Now imagine that several companies use your DLL, bylinking their application with your import library. Now imagine that youwant to update your DLL and rerelease it. If you modify the DLL such thatthe function ordinals change, then that DLL is no longer compatible withthe applications that use your DLL, since the import library they link touses the previous function ordinals.Of course, you could release a new import library so that all theapplications can be relinked, but this is not very realistic. The end userwill not want to load and install new revisions of all the applications thatuse the DLL in order for them to continue working (not to mention that ifthey forget to upgrade one, it will be likely to crash, or to do other harm).To solve this issue, you freeze the DLL interface before your initialrelease.

From then on, as you make changes to your DLL, the build toolswill keep the DLL ordinal numbers assigned to the same function names,as specified in the frozen interface. If you add new functions, they areassigned new ordinal numbers, with values above the existing ones in thefrozen interface.The old import library will, of course, not provide access to the newfunctions, but an application can still find the older ones that it uses, inthe same place as before.If you were to delete a function in your DLL, the order would belost – but the good news is that this is considered a violation of the frozeninterface and will generate a build error until you refreeze the interface.Disabling interface freezingInterface freezing should be disabled in early development.

Add EXPORTUNFROZEN to your DLL’s MMP file to do this. Building in this modeis straightforward – you run bldmake bldfiles and abld buildbuild target build type and it generates an updated DLL andimport library. However, since the interface is not frozen, all applicationsthat use your DLL must be relinked to the updated import library becausethe previous import library’s backward compatibility is not guaranteed.This is because the ordinals assigned to exported functions are freeto change with each build, so only using the import library and DLLproduced from the same build is safe.However, having the DLL’s ordinals change during early developmentis not an issue, since you have control over the applications that use theDLL. Many times you will build both the DLL and the applications thatuse it together at this stage, and the new import library will be picked upautomatically.Enabling interface freezingIn the later stages of DLL development, you’ll want to enable interfacefreezing in your builds and freeze the DLL’s exports each time you146SYMBIAN OS BUILD ENVIRONMENTrelease.

This will ensure that updates to your DLL will remain backwardcompatible with previously released import libraries.How do you do this? Remove the EXPORTUNFROZEN statement inyour MMP file. With this statement removed, the build will require thatthe DLL interface (i.e., exported function ordinals) be frozen. Then youperform an interface freeze with the abld freeze command each timeyou release a new DLL and import library.What does the abld freeze command do?It creates a DEF file that records the current exported interface of the DLL.The DEF file defines the frozen interface by listing each exported functionname along with its ordinal number.How is the DEF file used?With freezing enabled, each DLL project is associated with a DEF file (seethe note at the end of this section for how it is associated) that defineswhere the abld freeze writes to.

The build then uses this DEF file inthe following situations:• Linking the DLLWhen the DLL is built, the project’s frozen DEF file is consulted.The linker will ensure that all functions specified in the DEF file willremain at the same specified ordinal position, ensuring backwardcompatibility with the import library produced after the last freeze.New functions in the DLL will receive new, higher-numbered ordinals(which will be added to the DEF on the next freeze).• Generating the import libraryWith interface freezing enabled, the import library is generated directlyusing the DLL interface defined in the project’s DEF file.

Whileinterface freezing is disabled, the import library is always generatedusing the interface from the just-generated DLL.This is why the first build of a DLL will fail to generate an importlibrary if an abld freeze command was not done – no DEF file yetexists.•Associating a DEF file with your projectThe name of the DEF file associated with your project defaults to<your projectname>U.DEF and is located in your project’s EABI(for ARM build targets) or BWINS (for emulator build targets) directory.U stands for Unicode build in your BARM directory.

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

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

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

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