COM ArcObject passed to .NET library: how to cast, access and debug it

Posted by on January 4, 2007

Generally when developing your .NET ArcObjects library you are managing all .NET objects, because the ArcObjects are wrapped by the RCW, Runtime Callable Wrapper (preferably created by Esri, using the Primary Interoperability Assemblies, PIA, installed with ArcGIS desktop in the GAC).
You can then expose your .NET library to COM by a CCW, COM callable wrapper, creating a tlb with regasm (automatically done using Visual Studio if you check the ‘Register for COM interop’ option, under the Build tag of project’s property dialog).

Using the RCW ArcObjects we are always using Managed code, so we don’t get in troubles.

But what if a COM ArcObject is calling a method, sinking an event, or setting/getting a property from our .NET library?

This is the case that occours when ArcGis Desktop, or VBA or a COM ArcObjects library is calling the .NET library, like in the picture (blue arrow).

COM-NET ArcObjects communication
In that case a COM object is passed to our library, and we can’t for example investigate about its nature. We need a way to cast the COM object to a .NET object.

To do so, in C#, we can use the ‘as’ keyword to cast the COM object to a .NET one, without getting errors that could arise from explicit conversion.
After doing so we will be able to debug and access all the properties of this object.

Consider the following sample.
I have in my .NET library a class with this property:

IFeatureRenderer IGeoFeatureLayer.Renderer
{
get
{
return ((IGeoFeatureLayer)featureLayer).Renderer;
}
set
{
((IGeoFeatureLayer)featureLayer).Renderer = value;
checkRenderer(value);
}
}

When using the symbology dialog in ArcMap and after applying the changes to the layer, the set method is called and value (a COM object) is passed to my .NET library.If now I want to access and debug it I need to make a cast.

The cast is performed by the ‘as’ keyword like showed in the following code:

private void checkRenderer(object o)
{
IFeatureRenderer fr = o as IFeatureRenderer;
if (fr is IFeatureRenderer)
{
System.Diagnostics.Debug.WriteLine("IFeatureRenderer");
}
if (fr is ISimpleRenderer)
{
ISimpleRenderer sr = fr as ISimpleRenderer;
System.Diagnostics.Debug.WriteLine("ISimpleRenderer");
}
if (fr is IUniqueValueRenderer)
{
IUniqueValueRenderer uvr = fr as IUniqueValueRenderer;
System.Diagnostics.Debug.WriteLine("IUniqueValueRenderer");
//check the unique values class (supposing FieldCount=1)
for (int i = 0; i < uvr.ValueCount; i++)
{
System.Diagnostics.Debug.WriteLine(uvr.get_Field(0) + ", " + uvr.get_Value(i));
}
}
}
Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • Furl
  • LinkedIn
  • Reddit
  • StumbleUpon
0 Comments on COM ArcObject passed to .NET library: how to cast, access and debug it

Closed