How to: Use Native COM Servers with TLBIMP

Unlike other .NET languages, Visual C++ provides interop features that allow unmanaged functions, including COM interfaces, to be used directly. This allows developers to avoid Tlbimp.exe and its disadvantages. For more information, see Using Native COM Servers from .NET.

This topic demonstrates how COM objects can be used from managed code the Type Library Importer (Tlbimp.exe) tool. This .NET Framework tool, given a COM type library (or just the DLL containing both the COM component and the type library), generates an managed interop assembly that can be used from any .NET language. However, this technique, especially for large and/or complex COM type libraries, is not recommended for Visual C++ programmers.

The following example contains the steps and code required to use COM interfaces defined in Quartz.dll, which is installed in the Windows/System32 directory in Windows XP. These interfaces encapsulate DirectShow functionality to allow the playback of AVI files. To execute Tlbimp.exe from the command line, you need to add the .NET Framework tools to the system path by executing Sdkvars.bat in the C:\Program Files\Microsoft.NET\SDK\v2.0\Bin directory.

To generate the interop assembly

  1. In a command prompt window, in the c:\windows\system32 directory, execute the command tlbimp quartz.dll. (The name of the resulting interop assembly is based on the name of the COM type library; in this case the resulting file is QuartzTypeLib.dll.)

  2. Move the interop assembly to a directory where the application that uses it will be executed.

Example

The following code defines a console application that uses the previously generated interop assembly to display an AVI file.

Execute the resulting .exe file with the name of a valid AVI file, and the file is rendered in a window.

// AVIPlayer.cpp
// compile with: /clr
#using <QuartzTypeLib.dll>
using namespace QuartzTypeLib;

using namespace System;
   
void DisplayUsage() {
   Console::WriteLine("AVIPlayer: Plays AVI files."); 
   Console::WriteLine("Usage: AVIPlayer.EXE <filename>"); 
}

int main() { 
   array<String^>^ args = Environment::GetCommandLineArgs();
   if (args->Length != 2) {
      DisplayUsage();
      return 0;
   } 

   String^ filename = args[1]; 
   if (filename->Equals("/?")) { 
      DisplayUsage();
      return 0;
   }

   FilgraphManager^ graphManager = gcnew FilgraphManager();
   IMediaControl^ mc = dynamic_cast<IMediaControl^>(graphManager);

   mc->RenderFile(filename);
   mc->Run();

   Console::WriteLine("press any key");
   Console::ReadLine();
}

See Also

Reference

Using Native COM Servers from .NET