我们知道,常见的使用托管代码调用非托管代码的方法有P/Invoke, ComImport, 两者之间区别详见 http://*.com/questions/8911635/is-comimport-considered-p-invoke, 本文只讨论ComImport的情形。
1) 创建COM Class Wrapper
使用Window SDk 中的 TlbImp 来把Com 所定义的转换成 C#, 打开 command prompt run as administrator, 切换到目录 C:\Program Files(x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools,
Use ILSPY 反编译
2) 把该Assembly include 到项目中,可以创建 Com 对象,调用其方法。
static void Main(string[] args) { string fileName = @"d:\MyTest.mp3"; try { QuartzTypeLib.FilgraphManager graphManager = new QuartzTypeLib.FilgraphManager(); //QueryInterface for IMediaContorl interface QuartzTypeLib.IMediaControl mc = (QuartzTypeLib.IMediaControl)graphManager; //call some method on COM interface //Pass in file to RenderFile method on COM object mc.RenderFile(fileName); mc.Run(); } catch (Exception e) { Console.Write("Unexpected COM exception: " + e.Message); } Console.Read(); }
Since we know class identifier from disassemblied file,
我们可以如下方式创建实例
static QuartzTypeLib.FilgraphManager CreateFileGraphManager() { var mediaControlClsID = new Guid("E436EBB3-524F-11CE-9F53-0020AF0BA770"); var mediaControlType = Type.GetTypeFromCLSID(mediaControlClsID); return Activator.CreateInstance(mediaControlType) as QuartzTypeLib.FilgraphManager; }