Search code examples
c#.netreflectioncom

Search for COM object members via Reflection


I'm working with a COM object and I need to be able to search for properties and methods at runtime via Reflection and invoke them based on an input string that roughly matches the COM object's structure.

I'm currently using a recursive algorithm to walk the COM object's properties at runtime using obj.GetType().InvokeMember() but this only works if I'm supplied the exact property and method names, which is not always the case. Examples:

"ALPha.BETa.GAMma?" -> var gamma = comObj.ALPha.BETa.GAMma;
"ALP.BET.GAM?" -> var gamma = comObj.ALPha.BETa.GAMma;
"ALP.BET.GAM 200" -> comObj.ALPha.BETa.GAMma = 200;
"ALPha.DELta" -> comObj.ALPha.DELta();

(if anyone's familiar with SCPI, this is what I'm actually working with -- trying to dynamically convert SCPI strings to calls to a COM object's API at runtime)


Stray observations:

  • typeof(IComObject).GetProperties() only returns properties that have been previously evaluated at runtime which is useless for me.
  • Intellisense is fully available for all properties and methods on the COM object.
  • The debugger shows comObj's type as System.__ComObject at runtime.
  • I've tried running Tlbimp.exe on the COM type library exe to produce an interop assembly but I see the same results as before when using GetProperties().
  • There's at least 200 properties and methods on the COM object so there's no way I can manually build up the mappings.

Solution

  • To expand on @HansPassant comment, COM just doesn't do reflection. Late-binding COM (via IDispatch) is done via exact string match. Probably your best bet is to decode the typelib yourself (I'd start with this tool) and build a manual mapping from strings to methods and properties. (Yes, you're manually reimplementing reflection.)