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

Основы описания

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

Adjusting the Definition

Whether you set them explicitly or not, attribute fields are at work defining the behavior of managed code. Platform invoke operates according to the default values set on various fields that exist as metadata in an assembly. You can alter this default behavior by adjusting the values of one or more fields. In many cases, you use the DllImportAttribute to set a value.

The following table lists the complete set of attribute fields that pertain to platform invoke. For each field, the table includes the default value and a link to information on how to use these fields to define unmanaged DLL functions.

Field

Description

BestFitMapping

Enables or disables best-fit mapping.

CallingConvention

Specifies the calling convention to use in passing method arguments. The default is WinAPI, which corresponds to __stdcall for the 32-bit Intel-based platforms.

CharSet

Controls name mangling and the way that string arguments should be marshaled to the function. The default is CharSet.Ansi.

EntryPoint

Specifies the DLL entry point to be called.

ExactSpelling

Controls whether an entry point should be modified to correspond to the character set. The default value varies by programming language.

PreserveSig

Controls whether the managed method signature should be transformed into an unmanaged signature that returns an HRESULT and has an additional [out, retval] argument for the return value.

The default is true (the signature should not be transformed).

SetLastError

Enables the caller to use the Marshal.GetLastWin32Error API function to determine whether an error occurred while executing the method. In Visual Basic, the default is true; in C# and C++, the default is false.

ThrowOnUnmappableChar

Controls throwing of an exception on an unmappable Unicode character that is converted to an ANSI "?" character.

Настройка описания

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

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

Поле

Описание

BestFitMapping

Включает и отключает наилучшее сопоставление.

CallingConvention

Задает соглашение о вызовах, которое должно использоваться при передаче аргументов методов. По умолчанию используется значение WinAPI, соответствующее режиму __stdcall для 32-разрядных платформ на основе процессора Intel.

CharSet

Управляет изменением имен при передаче и задает способ маршалинга строковых аргументов в функцию. По умолчанию используется CharSet.Ansi.

EntryPoint

Задает точку входа DLL для вызова.

ExactSpelling

Определяет, должна ли изменяться точка входа в соответствии с кодировкой. Значение зависит от языка программирования.

PreserveSig

Определяет, должна ли управляемая подпись метода преобразоваться в неуправляемую подпись, которая возвращает значение HRESULT и для возвращаемого значения имеет дополнительный аргумент [out, retval].

По умолчанию используется значение true (подпись не должна преобразовываться).

SetLastError

Позволяет вызывающему объекту при выполнении метода для определения факта ошибки использовать функцию интерфейса API Marshal.GetLastWin32Error. В Visual Basic по умолчанию используется значение true, в C# и C++ — значение false.

ThrowOnUnmappableChar

Управляет возникновением исключения при появлении несопоставимого символа Юникода, который преобразуется в символ ANSI "?".

Specifying an Entry Point

An entry point identifies the location of a function in a DLL. Within a managed project, the original name or ordinal entry point of a target function identifies that function across the interoperation boundary. Further, you can map the entry point to a different name, effectively renaming the function.

Following is a list of possible reasons to rename a DLL function:

  • To avoid using case-sensitive API function names

  • To comply with existing naming standards

  • To accommodate functions that take different data types (by declaring multiple versions of the same DLL function)

  • To simplify using APIs that contain ANSI and Unicode versions

This topic demonstrates how to rename a DLL function in managed code.

Renaming a Function in C# and C++

You can use the DllImportAttribute..::.EntryPoint field to specify a DLL function by name or ordinal. If the name of the function in your method definition is the same as the entry point in the DLL, you do not have to explicitly identify the function with the EntryPoint field. Otherwise, use one of the following attribute forms to indicate a name or ordinal:

[DllImport("dllname", EntryPoint="Functionname")]

[DllImport("dllname", EntryPoint="#123")]

Notice that you must prefix an ordinal with the pound sign (#).

The following example demonstrates how to replace MessageBoxA with MsgBox in your code by using the EntryPoint field.

using System.Runtime.InteropServices;

public class Win32 {

[DllImport("user32.dll", EntryPoint="MessageBoxA")]

public static extern int MsgBox(int hWnd, String text, String caption, uint type);

}