162
❘
CHAPTER 9
InteractIng wIth cOM Objects
components using several different techniques — two of which rely on late binding
Activator
.CreateInstance()
and
Marshal.GetActiveObject()
.
In short, you
can access COM components
in numerous ways, and this chapter discusses a few of the more popular techniques that the .NET
developer is likely to know about.
AN OvERvIEW Of COM ACCESS DIffERENCES WITH PyTHON
COM access is an area where IronPython and Python take completely different approaches. In fact, it’s
safe to say that any Python code you want to use definitely won’t work in IronPython. Python develop-
ers normally rely on a library such as Python for Windows Extensions (
http://sourceforge.net/
projects/pywin32/
). This is a library originally created by Mark Hammond (
http://starship
.python.net/crew/mhammond/win32/
) that includes not only the COM
support but also a really
nice Python editor. You can see a basic example of using this library to access COM at
http://www
.boddie.org.uk/python/COM.html
. Even if you download the required library
and try to follow the
tutorial, you won’t get past step 1. The tutorial works fine with standard Python, but doesn’t work at
all with IronPython.
It’s important to remember that IronPython is a constantly moving target. The
developers who support IronPython constantly come out with new features and
functionality, as do the third parties that support it. You may find at some point
that there’s a COM interoperability solution that does work for both Python
and IronPython. The solution doesn’t exist today, but there’s always hope for
tomorrow. If you do encounter such a solution, please be sure to contact me at
JMueller@mwt.net
.
Fortunately, IronPython developers aren’t left out in the cold. COM support is built right into
IronPython in the form of the .NET Framework. An IronPython developer uses the same tech-
niques as a C# or a Visual Basic.NET developer uses to access COM — at least at a code level.
When you work with COM in Visual Studio in either a C# or Visual Basic.NET project, the IDE does
a lot of the work for you. If you want to use a COM
component in your application,
you right-click
References in Solution Explorer and choose Add Reference from the context menu. At this point, you
see the Add Reference dialog box where you choose the COM tab shown in Figure 9-1.
When you highlight an item, such as the Windows Media Player, and click OK, the IDE adds the
COM component to the References folder of Solution Explorer, as shown in Figure 9-2. The IDE
writes code for you in the background that adds the COM component and makes it accessible.
You’ll find this code in the .CSProj file and it looks something like this:
{22D6F304-B0F6-11D0-94AB-0080C74C7E95}
1
0
0
tlbimp
548592c09.indd 162
2/24/10 12:48:16 PM
www.finebook.ir