348
❘
CHAPTER 16
ExtEnding ironPython Using C#
USINg C# foR WIN32 SUPPoRT
The Python language doesn’t really support much in the way of platform-specific functionality and
that’s by design. One of the tenets of cross-platform compatibility is not to make an issue out of the
platform on which the code runs. However, in some cases, you really do need to access the platform
and discover things about it. For example, you might want to know more about the environment in
which your application is executing, such as the size of the console window. You might even want to
clear the console window (a feature that is missing from the IronPython console, without which your
sessions can appear messy). An application may need to know something about the security in place
for the current session. In short, you might have many reasons for wanting to know something more,
but Python (and by extension, IronPython) largely lacks the functionality to provide this information.
The example in the following sections plays to a strength of C#, which is to interact with the
Windows platform through a feature called Platform Invoke (P/Invoke). This example goes outside
the managed .NET environment and relies on the Win32 API to access Windows functionality that
you can’t access through .NET.
Creating the P/Invoke Code
Before you can write any P/Invoke code, you need to add the following
using
statement.
using System.Runtime.InteropServices;
This statement provides access to the various special programming features that C# provides for
accessing the Win32 API.
You may find that you have little interest in precisely how P/Invoke works.
It’s possible to skip the details found in this section, proceed to the sections
that follow, and still understand how the whole application works. However,
working through the P/Invoke code will give you a better understanding of the
power that C# provides in accessing features you might not have used in the
past (and potentially a few that you might not even know exist now).
If you haven’t worked with the Win32 API in the past, you might find the use of structures, enumera-
tions, and pointers confusing. In reality, all these events take place somewhere in the background
when you execute any application. At some point, your managed code ends up interacting with the
Win32 API to perform tasks because the basic Windows DLLs still rely on the Win32 API. Normally,
CLR hides all these details from view so you don’t need to worry about them. Listing 16-5 shows the
Win32 API access code — the lower-level code that does all the hard work for this example.
Do'stlaringiz bilan baham: