开发者

Get A GUID by Type Name

So I'm trying to do manually what AxImp does (I'm doing it dynamically).

My product is a wide released, sanctioned "add-on" to a third party product. They hav开发者_开发问答e an OCX, which I add to my form with a COM reference...however, if the client has (or installs) an updated version of their product my product can no longer load the OCX.

Therefore I'm trying to load their OCX dynamically. I've got everything working except that I need the GUID of one of the interfaces in one of their OCXs. I know what the type name is, and the OCX >is< registered on the system. How can I get an object's GUID just from the type name?

Note, Assembly.LoadFrom() doesn't work because the OCX isn't .NET it's COM.


Since your comment let us know that the GUID is found in the OCX but not registered under HKEY_CLASSES_ROOT, we'll have to read it from the type library:

  • Call LoadTypeLib or LoadTypeLibEx, passing the path to the .OCX file

  • Then use the FindName method of the returned object.

  • Then GetTypeAttr followed by PtrToStructure to get a TYPEATTR structure with the GUID.


Not sure why you can't simply add a COM reference to the DLL to your project.

Visual Studio will automatically add a .NET wrapper to any COM object that is referenced this way.


I had to write something like that to migrate code from COM to C#

class GetGuid
{
    [DllImport("oleaut32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
    static extern int LoadTypeLib(string fileName, out ITypeLib typeLib);

    public string SearchRegistry(string dllPath /* or ocx */)
    {
        var result = string.Empty;
        ITypeLib tl;
        if (LoadTypeLib(dllPath, out tl) == 0)
        {
            ITypeInfo tf;
            tl.GetTypeInfo(0, out tf);

            var ip = IntPtr.Zero;
            tl.GetLibAttr(out ip);

            if (ip != IntPtr.Zero)
            {
                var ta = (System.Runtime.InteropServices.ComTypes.TYPELIBATTR)Marshal.PtrToStructure(ip, typeof(System.Runtime.InteropServices.ComTypes.TYPELIBATTR));
                result = ta.guid.ToString();
            }
        }
        return result;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜