Creating a Class to Hold DLL Functions



Wrapping a frequently used DLL function in a managed class is an effective approach to encapsulate platform functionality. Although it is not mandatory to do so in every case, providing a class wrapper is convenient because defining DLL functions can be cumbersome and error-prone. If you are programming in Visual Basic or C#, you must declare DLL functions within a class or Visual Basic module.

Within a class, you define a static method for each DLL function you want to call. The definition can include additional information, such as the character set or the calling convention used in passing method arguments; by omitting this information, you select the default settings.

Once wrapped, you can call methods on the function as you call methods on any other static function. Platform invoke handles the underlying exported function automatically.

When designing a managed class for platform invoke, consider the relationships between classes and DLL functions. For example, you can:

· Declare DLL functions within an existing class.

· Create an individual class for each DLL function, keeping functions isolated and easy to find.

· Create one class for a set of related DLL functions to form logical groupings and reduce overhead.

You can name the class and its methods as you please.

 


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

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

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

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

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

· Объявлять функции DLL в существующем классе.

· Создавать для каждой функции 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.


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

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






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