Consuming Unmanaged DLL Functions



Platform invoke is a service that enables managed code to call unmanaged functions implemented in dynamic link libraries (DLLs), such as those in the Win32 API. It locates and invokes an exported function and marshals its arguments (integers, strings, arrays, structures, and so on) across the interoperation boundary as needed.

This section introduces several tasks associated with consuming unmanaged DLL functions. In addition to the following tasks, there are general considerations and a link providing additional information and examples.

To consume exported DLL functions

1. Identify functions in DLLs.

Minimally, you must specify the name of the function and name of the DLL that contains it.

2. Create a class to hold DLL functions.

You can use an existing class, create an individual class for each unmanaged function, or create one class that contains a set of related unmanaged functions.

3. Create prototypes in managed code.

 [C#] Use the DllImportAttribute to identify the DLL and function. Mark the method with the static and extern modifiers.

4. Call a DLL function.

Call the method on your managed class as you would any other managed method. Passing structures and implementing callback functions are special cases.

 


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

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

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

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

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

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

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

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

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

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

4. Вызовите функцию 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.


Дата добавления: 2019-03-09; просмотров: 237; Мы поможем в написании вашей работы!

Поделиться с друзьями:






Мы поможем в написании ваших работ!