23

I have an interface defined in an IDL file that I would like to use in C#. Is there a way to convert the IDL to something usable in C#?

Jon Tackabury
  • 47,710
  • 52
  • 130
  • 168

3 Answers3

34

One way is to run MIDL on the IDL to create a type library (.tlb). This requires a library block in the IDL. Once you have the .tlb, you can run tlbimp.exe on it to get a C# definition/Interop DLL.

Vinay Sajip
  • 95,872
  • 14
  • 179
  • 191
  • 1
    and you then you can use [JetBrains dotPeek](https://www.jetbrains.com/decompiler/) to view the C# definition from the generated interop DLL. – Greg Thatcher Jun 02 '16 at 22:33
6

What datatypes/structures are used in the IDL? You should first define the datatypes in C# first if there is no inbuild type already.

You can use the following tool to convert the structures, but you need to verify the ouput manually.

Download: http://download.microsoft.com/download/f/2/7/f279e71e-efb0-4155-873d-5554a0608523/CLRInsideOut2008_01.exe

This utility is described at Accessing Windows API Constants and Structs for P/Invoke.

The original January 2008 article is now only available as a .CHM help file download, linked at the bottom of https://msdn.microsoft.com/magazine/msdn-magazine-issues. For the time being, the source code can be found at http://clrinterop.codeplex.com/.

Glenn Slayden
  • 17,543
  • 3
  • 114
  • 108
DevByDefault
  • 664
  • 10
  • 24
2

For example, I've recently used the XPS Print API and needed the xpsobjectmodel.h interfaces. The Windows SDK comes with xpsobjectmodel.idl fortunately.

I generated the TLB file with MIDL first and used TLBIMP to generate a proper DLL assembly ready to be added in the 'References...' section in my C# project.

Be sure to use the tools with the correct version for your project framework. e.g, if your project framework is 3.5-based, using tlbimp from the 4.0 toolset won't work.

Hernán
  • 4,527
  • 2
  • 32
  • 47