Interop introduction

.NET provides interop services to use COM components (with RCW) or native DLL (with P/Invoke).

For using COM components on .NET, there are two choices: early binding and late binding.

Usual way to do COM interop with C# is an example of early binding. CreateObject a la VB uses late binding. If you know CPython's win32all extension, early binding corresponds to using makepy utility, and late binding to win32com.client.Dispatch.

Once you have a COM object, the usage from IronPython differs little. IronPython tries hard to hide the lack of type information in the late binding case.

For early binding, you create the interop DLL from the type library. This DLL contains strongly typed proxy classes for COM, and you can use it as any other managed assembly.

One uses tlbimp to create the interop DLL. It comes as part of the .NET 2.0 SDK, or with Visual Studio. You want to add the directory containing tlbimp.exe to PATH. For .NET 2.0 SDK, this is C:\Program Files\Microsoft.NET\SDK\v2.0\Bin. For Visual Studio, use C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin.

Here is an example running tlbimp: tlbimp %SystemRoot%\system32\shell32.dll /out:Interop.Shell32.dll

Run tlbimp /? for more options.

For late binding, you create .NET Type from ProgID, and use Activator to create an instance of the type. Following example illustrates this usage:

from System import Activator, Type shell = Activator.CreateInstance(Type.GetTypeFromProgID('Shell.Application'))

Another usage is to control an already running instance of COM object. This is done using Marshal.

from System.Runtime.InteropServices import Marshal excel = Marshal.GetActiveObject('Excel.Application')

Back to Contents.