Using C# for Win32 Support ❘
351 developing the IronPython Callable methods The P/Invoke code shown in Listing 16-5 does expose the Win32 API calls needed to perform cer-
tain tasks with IronPython. Theoretically, you could rely on just the code in Listing 16-5 to gain the
access you require in IronPython. However, the task would be difficult because you’d need to work
through the required bit manipulations. It’s better to place the code you need to access the Win32
API in easily called methods, which is the purpose of the code in the following sections.
Defining Common Variables and the Constructor Win32 API calls often reuse information. It’s not uncommon for functions to ask for the same infor-
mation over and over. For example, any function that works with a window will probably need the
handle for that window. With this requirement in mind, Listing 16-6 shows the common variables
and the constructor used for this example.
LISTINg 16-6: Common variables and constructor UInt32 DisplayMode = 0; // The current display mode.
IntPtr hOut; // Handle to the output device.
IntPtr hIn; // Handle to the input device.
UInt32 ConsoleMode = 0; // The console mode information.
public ConMode()
{
// Obtain a handle to the console screen and console input.
hIn = GetStdHandle(StdHandleEnum.STD_INPUT_HANDLE);
hOut = GetStdHandle(StdHandleEnum.STD_OUTPUT_HANDLE);
}
The common variables include the current display mode (such as windowed), the console mode
information (such as whether it accepts mouse input), and the handles for the input and output
devices. These variables represent common pieces of information that the developer requires for
multiple calls.
The constructor initializes the input and output handles using the
GetStdHandle()
function. The
input argument simply tells Windows which handle you want. The output is an
IntPtr
, a special
kind of variable that points to something. An
IntPtr
is a safe pointer, meaning you can use it with-
out problems in a managed language. C# also supports unsafe pointers that you should use only as a
last resort.
An IntPtr
provides an integer value that represents a pointer. The size of the integer is platform-specific and you should never view a standard Int16
or Int32
type as an acceptable substitute. Always use an IntPtr
when you need to access a pointer or handle supplied by a Win32 API call. 548592c16.indd 351
2/24/10 12:49:27 PM
www.finebook.ir