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#?
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.
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.
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/.
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.
来源:https://stackoverflow.com/questions/1307675/convert-interface-idl-file-to-c-sharp