3

I have a COM DLL written in Visual C++. I fully control that COM DLL code. Of course it can be consumed from both managed and unmanaged applications. I want to insert a very specific check that should only be run when the COM DLL is consumed by a .NET application.

Is there some programmatic way for my COM object to detect whether it is being consumed from a .NET application or from an unmanaged application?

sharptooth
  • 167,383
  • 100
  • 513
  • 979
  • @sharptooth I have no idea if it's possible, but I'd love to know why you want to? – aphoria May 17 '11 at 12:24
  • @aphoria: We want to insert an extra check that is only needed when it is used from a .NET application and would hurt otherwise. – sharptooth May 17 '11 at 12:27
  • It does seem like a rather odd question. Maybe you could check if mscoree.dll is loaded, though I'm not sure how reliable of an indicator that is. See http://stackoverflow.com/questions/2080046/how-to-check-if-a-program-is-using-net for example (I like wj32's answer). – Luke May 17 '11 at 12:40
  • @sharptooth: Can you be more specific about that check? Normally, the called COM object shouldn't care what technology is used to implement the caller. – Daniel Hilgarth May 17 '11 at 12:44
  • @Daniel Hilgarth: What I want to check is not that critical - I just want to write an if-statement and don't know which condition to check. – sharptooth May 17 '11 at 12:46
  • @sharptooth: I want to understand why this check is needed at all. In other words: Why do you care which technology calls you? – Daniel Hilgarth May 17 '11 at 12:47
  • @Daniel Hilgarth: There're some differences between managed and unmanaged in handling COM interfaces if a library is loaded directly and first object is created by calling an exported function marked `DllImport` instead of using `new` in C#. That's a bad solution, but we have to maintain it. – sharptooth May 17 '11 at 12:53

2 Answers2

2

These kind of "what's my environment" questions always have the same answer. Your host has no trouble figuring out if it is managed, just add a property to your interface to let it tell you. A trivial solution compared with the alternative. Which is impossible to implement reliably in COM, lots of ways to host a server.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • +1 This is a very good point. It's tempting to over-engineer a cool, slick solution when a simple one would work. (Something I struggle with.) This doesn't technically answer the question, but maybe it's not possible and this is the best solution. – Richard Brightwell May 27 '11 at 01:38
1

Two possibilities:

  1. Create a native .NET assembly wrapping the COM object and initializing it appropriately
  2. Try to detect whether your process is a .NET process and live with the problems (no mono detection, false positives, most likely invalid detection when used in the context of DCOM/COM+)
Community
  • 1
  • 1
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443