Search code examples
c#comcom-interop

Why cannot I cast com object in c#?


The source code:

   IMoniker moniker;
    int hresult = NativeMethods.CreateFileMoniker(kFileName, out moniker);
    IBindCtx pbc;
    NativeMethods.CreateBindCtx(0, out pbc);
    Object obj;
    Guid guid = new Guid();
    guid = typeof(GraphicsLibrary.IPolyline).GUID;
    moniker.BindToObject(pbc, null, guid, out obj);
    GraphicsLibrary.IPolyline pl = (GraphicsLibrary.IPolyline)obj;
    GraphicsLibrary.PolylineObjClass o = (GraphicsLibrary.PolylineObjClass)pl;
    foreach (GraphicsLibrary.PolyPoint ptt in o.Points)
    {
        Trace.WriteLine(String.Format("point ({0}, {1})", ptt.x, ptt.y));
    }
    return 0;

Exception on GraphicsLibrary.PolylineObjClass o = (GraphicsLibrary.PolylineObjClass)pl;

Detail:

An exception of type 'System.InvalidCastException' occurred in DotNetClient.exe but was not handled in user code

But I have implemented the IProvideClassInfo interface and did register the typelib.

Why cannot I cast the object?

PS: full source code, please refer https://github.com/Jichao/comtut/tree/master/monikers/FileMoniker


Solution

  • Your object is an implementation of IPolyline and do not comes from any superclass of PolylineObjClass or PolylineObjClass itself.

    • A implements IPolyline
    • B implements IPolyline
    • myFirstObj = new B();
    • mySecondObj = (A) myFirstObj; <= Failure, because B might implements other methods or properties A doesn't, so impossible to cast
    • mySecondObj = (IPolyline) myFirstObj; <= work, you are limited the cast to the same scope of methods.