logo search
CSharp_Prog_Guide

Создание класса, содержащего функции dll

Заключение часто используемой функции DLL в оболочку управляемого класса представляет собой эффективный способ инкапсуляции функциональных возможностей платформы. Хотя применение оболочки класса необязательно, оно удобно, так как процесс определения функций DLL может быть громоздким и представлять собой источник ошибок. При программировании на Visual Basic или C# функции DLL должны объявляться в пределах класса или модуля Visual Basic.

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

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

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

Разработчик может назвать класс и его методы по своему усмотрению.

Creating Prototypes in Managed Code

This topic describes how to access unmanaged functions and introduces several attribute fields that annotate method definition in managed code. For examples that demonstrate how to construct .NET-based declarations to be used with platform invoke, see Marshaling Data with Platform Invoke.

Before you can access an unmanaged DLL function from managed code, you need to know the name of the function and the name of the DLL that exports it. With this information, you can begin to write the managed definition for an unmanaged function that is implemented in a DLL. Furthermore, you can adjust the way that platform invoke creates the function and marshals data to and from the function.

Note:

Win32 API functions that allocate a string enable you to free the string by using a method such as LocalFree. Platform invoke handles such parameters differently. For platform invoke calls, make the parameter an IntPtr type instead of a String type. Use methods that are provided by the System.Runtime.InteropServices..::.Marshal class to convert the type to a string manually and free it manually.

Declaration Basics

Managed definitions to unmanaged functions are language-dependent, as you can see in the following examples. For more complete code examples, see Platform Invoke Examples.