Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharp_Prog_Guide.doc
Скачиваний:
16
Добавлен:
16.11.2019
Размер:
6.22 Mб
Скачать

Использование неуправляемых функций dll

Вызов неуправляемого кода — это служба, которая позволяет управляемому программному коду вызывать неуправляемые функции, реализованные в библиотеках динамической компоновки (DLL), например, функции библиотек Win32 API. Вызов неуправляемого кода обнаруживает и вызывает экспортируемую функцию и при необходимости выполняет маршалинг ее аргументов (целых чисел, строк, массивов, структур и так далее) через границы взаимодействия.

В этом разделе представлено несколько задач, связанных с использованием неуправляемых функций DLL. Кроме следующих задач, имеются общие аспекты и ссылка, указывающая на дополнительные сведения и примеры.

Применение экспортированных функций dll

  1. Идентифицируйте функции в DLL.

Как минимум, должно быть указано имя функции и имя библиотеки DLL, содержащей функцию.

  1. Создайте класс для хранения функций DLL.

Можно использовать существующий класс, создать отдельный класс для каждой неуправляемой функции либо создать один класс для всего набора связанных неуправляемых функций.

  1. Создайте прототипы в управляемом коде.

[C#] Чтобы идентифицировать DLL и функцию, используйте класс DllImportAttribute. Пометьте метод модификаторами static и extern.

  1. Вызовите функцию DLL.

Вызовите метод созданного управляемого класса так же, как любой другой управляемый метод. Особыми случаями являются передача структур и реализация функций обратного вызова.

A Closer Look at Platform Invoke

Platform invoke relies on metadata to locate exported functions and marshal their arguments at run time. The following illustration shows this process.

A platform invoke call to an unmanaged DLL function

When platform invoke calls an unmanaged function, it performs the following sequence of actions:

  1. Locates the DLL containing the function.

  2. Loads the DLL into memory.

  3. Locates the address of the function in memory and pushes its arguments onto the stack, marshaling data as required.

    Note:

    Locating and loading the DLL, and locating the address of the function in memory occur only on the first call to the function.

  4. Transfers control to the unmanaged function.

Platform invoke throws exceptions generated by the unmanaged function to the managed caller.

Подробный обзор вызова неуправляемого кода

Для нахождения экспортируемых функций и маршалинга их аргументов во время выполнения вызов неуправляемого кода использует метаданные. Этот процесс показан на следующем рисунке.

Вызов неуправляемой функции DLL из вызова неуправляемого кода

При вызове неуправляемой функции вызов неуправляемого кода выполняет следующую последовательность действий:

  1. Определяет DLL, содержащую функцию.

  2. Загружает DLL в память.

  3. Находит адрес функции в памяти и помещает ее аргументы в стек, осуществив в случае необходимости маршалинг данных.

    Примечание.

    Обнаружение и загрузка DLL, а также определение адреса функции в памяти выполняется только при первом вызове функции.

  4. Передает управление неуправляемой функции.

Исключения, возникающие при вызове неуправляемой функции, передаются управляемому вызывающему коду.

Identifying Functions in DLLs

The identity of a DLL function consists of the following elements:

  • Function name or ordinal

  • Name of the DLL file in which the implementation can be found

For example, specifying the MessageBox function in the User32.dll identifies the function (MessageBox) and its location (User32.dll, User32, or user32). The Microsoft Windows application programming interface (Win32 API) can contain two versions of each function that handles characters and strings: a 1-byte character ANSI version and a 2-byte character Unicode version. When unspecified, the character set, represented by the CharSet field, defaults to ANSI. Some functions can have more than two versions.

MessageBoxA is the ANSI entry point for the MessageBox function; MessageBoxW is the Unicode version. You can list function names for a specific DLL, such as user32.dll, by running a variety of command-line tools. For example, you can use dumpbin /exports user32.dll or link /dump /exports user32.dll to obtain function names.

You can rename an unmanaged function to whatever you like within your code as long as you map the new name to the original entry point in the DLL. For instructions on renaming an unmanaged DLL function in managed source code, see the Specifying an Entry Point.

Platform invoke enables you to control a significant portion of the operating system by calling functions in the Win32 API and other DLLs. In addition to the Win32 API, there are numerous other APIs and DLLs available to you through platform invoke.

The following table describes several commonly used DLLs in the Win32 API.

DLL

Description of Contents

GDI32.dll

Graphics Device Interface (GDI) functions for device output, such as those for drawing and font management.

Kernel32.dll

Low-level operating system functions for memory management and resource handling.

User32.dll

Windows management functions for message handling, timers, menus, and communications