logo
CSharp_Prog_Guide

Применение экспортированных функций 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.