通过PIA接口类型获取CLSID

时间:2010-04-14 02:32:39

标签: c# com

修改:看起来Jon Skeet有类似的问题:How does the C# compiler detect COM types?

如何在主Interop程序集中获取给定接口的CLSID?这就是我所说的:

// The c# compiler does some interesting magic.
// The following code ...
var app = new Microsoft.Office.Interop.Outlook.Application();

// ... is compiled like so (disassembled with Reflector):
var app =((Microsoft.Office.Interop.Outlook.Application)
  Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("0006F03A-0000-0000-C000-000000000046"))));


Microsoft.Office.Interop.Outlook.Application是一个接口,因此无法直接实例化。这里有趣的是,c#允许您将这些COM接口视为可以使用new关键字实例化的类。

我想知道的是,给定接口的System.Type,我如何获得CLSID?

注意:我最终希望能够在界面System.Type的情况下创建实例 - 我真的不在乎如何。我在这里假设最简单的方法是获得给定类型的CLSID,就像c#编译器一样。

2 个答案:

答案 0 :(得分:2)

这是我目前的解决方案:

// Get the PIA assemby name, using the GUID of the typlib
string asmName;
string asmCodeBase;
var conv = new System.Runtime.InteropServices.TypeLibConverter();
conv.GetPrimaryInteropAssembly(new Guid("00062FFF-0000-0000-C000-000000000046"), 9, 3, 0, out asmName, out asmCodeBase);

// Load the PIA, and get the interface type
var assembly = System.Reflection.Assembly.Load(asmName);
var type = assembly.GetType("Microsoft.Office.Interop.Outlook.Application");

// Get the coclass
var coClassAttr = (System.Runtime.InteropServices.CoClassAttribute)
    type.GetCustomAttributes(typeof(System.Runtime.InteropServices.CoClassAttribute), false)[0];
var coClass = coClassAttr.CoClass;

// Instantiate the coclass
var app = Activator.CreateInstance(coClassAttr.CoClass);

// If needed, the CLSID is also available:
var clsid = coClass.GUID;

我通过拆卸GAC的PIA来解决这个问题。我注意到Outlook.Application装饰有CoClassAttribute,如此:

[ComImport, Guid("00063001-0000-0000-C000-000000000046"), CoClass(typeof(ApplicationClass))]
public interface Application : _Application, ApplicationEvents_11_Event
{
}

ApplicationClass看起来像:

[ComImport, ClassInterface((short) 0), ComSourceInterfaces("Microsoft.Office.Interop.Outlook.ApplicationEvents_11\0Microsoft.Office.Interop.Outlook.ApplicationEvents\0Microsoft.Office.Interop.Outlook.ApplicationEvents_10\0"), Guid("0006F03A-0000-0000-C000-000000000046"), TypeLibType((short) 11)]
public class ApplicationClass : _Application, Application, ApplicationEvents_11_Event, ApplicationEvents_Event, ApplicationEvents_10_Event
{
    //...
}

让我知道你们都在想什么,所以我可以决定是否应该把它标记为选择的答案。

答案 1 :(得分:0)

尝试GUID属性。