Declaring and Passing Structures 


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



ЗНАЕТЕ ЛИ ВЫ?

Declaring and Passing Structures



The following example shows how to define the Point and Rect structures in managed code, and pass the types as parameter to the PtInRect function in the User32.dll file. PtInRect has the following unmanaged signature:

BOOL PtInRect(const RECT *lprc, POINT pt);

Notice that you must pass the Rect structure by reference, since the function expects a pointer to a RECT type.

using System.Runtime.InteropServices;   [StructLayout(LayoutKind.Sequential)] public struct Point { public int x; public int y; }   [StructLayout(LayoutKind.Explicit)] public struct Rect { [FieldOffset(0)] public int left; [FieldOffset(4)] public int top; [FieldOffset(8)] public int right; [FieldOffset(12)] public int bottom; }   class Win32API { [DllImport("User32.dll")] public static extern bool PtInRect(ref Rect r, Point p); }

Эта таблица содержит следующие указания для объявлений вызовов неуправляемого кода:

· Если неуправляемая функция не требует косвенного обращения, структуру следует передавать по значению.

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

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

Объявление и передача структур

В следующем примере показано определение структур Point и Rect в управляемом коде и передача типов в качестве параметра функции PtInRect в файле библиотеки User32.dll. Для функции PtInRect используется следующая неуправляемая подпись:

BOOL PtInRect(const RECT *lprc, POINT pt);

Обратите внимание, что структуру Rect следует передавать по ссылке, так как функция должна получить указатель на тип RECT.

ß------


Delcaring and Passing Classes

You can pass members of a class to an unmanaged DLL function, as long as the class has a fixed member layout. The following example demonstrates how to pass members of the MySystemTime class, which are defined in sequential order, to the GetSystemTime in the User32.dll file. GetSystemTime has the following unmanaged signature:

void GetSystemTime(SYSTEMTIME* SystemTime);

Unlike value types, classes always have at least one level of indirection.

[StructLayout(LayoutKind.Sequential)] public class MySystemTime { public ushort wYear; public ushort wMonth; public ushort wDayOfWeek; public ushort wDay; public ushort wHour; public ushort wMinute; public ushort wSecond; public ushort wMilliseconds; } class Win32API { [DllImport("Kernel32.dll")] public static extern void GetSystemTime(MySystemTime st); }

 


Объявление и передача классов

Если для класса используется фиксированное размещение членов, их можно передавать в неуправляемую функцию DLL,. В следующем примере демонстрируется передача последовательно упорядоченных в определении членов класса MySystemTime в функцию GetSystemTime в файле User32.dll. Для функции GetSystemTime используется следующая неуправляемая подпись:

void GetSystemTime(SYSTEMTIME* SystemTime);

В отличие от типов значений для классов всегда используется, по крайней мере, один уровень косвенного обращения.

ß----


File and Stream I/O

The System.IO namespace contains types that allow synchronous and asynchronous reading and writing on data streams and files.

The following distinctions help clarify the differences between a file and a stream. A file is an ordered and named collection of a particular sequence of bytes having persistent storage. Therefore, with files, one thinks in terms of directory paths, disk storage, and file and directory names. In contrast, streams provide a way to write and read bytes to and from a backing store that can be one of several storage mediums. Just as there are several backing stores other than disks, there are several kinds of streams other than file streams. For example, there are network, memory, and tape streams.

Basic File I/O

The abstract base class Stream supports reading and writing bytes. Stream integrates asynchronous support. Its default implementations define synchronous reads and writes in terms of their corresponding asynchronous methods, and vice versa.

All classes that represent streams inherit from the Stream class. The Stream class and its derived classes provide a generic view of data sources and repositories, isolating the programmer from the specific details of the operating system and underlying devices.

Streams involve these fundamental operations:

· Streams can be read from. Reading is the transfer of data from a stream into a data structure, such as an array of bytes.

· Streams can be written to. Writing is the transfer of data from a data source into a stream.

· Streams can support seeking. Seeking is the querying and modifying of the current position within a stream.

Depending on the underlying data source or repository, streams might support only some of these capabilities. For example, NetworkStreams do not support seeking. The CanRead, CanWrite, and CanSeek properties of Stream and its derived classes determine the operations that various streams support.

 



Поделиться:


Последнее изменение этой страницы: 2017-01-19; просмотров: 87; Нарушение авторского права страницы; Мы поможем в написании вашей работы!

infopedia.su Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Обратная связь - 18.218.218.230 (0.006 с.)