24

I just want to use .NET Profiling API (ICorProfilerCallback etc) but at the same time don't want to deal with C++. I've been looking around for a while and haven't found any example in C# but C# + C++ where the most interesting part is written using C++.

valiano
  • 16,433
  • 7
  • 64
  • 79
Alex LaWay
  • 435
  • 4
  • 7
  • 1
    You want to find bottlenecks, or memory leaks? If the former, you should be aware of [this technique](http://stackoverflow.com/questions/375913/what-can-i-use-to-profile-c-code-in-linux/378024#378024). It's effective and doesn't need an API, only a debugger. – Mike Dunlavey Apr 20 '11 at 21:34
  • what problem do you have with C++? what is your scenario? –  May 24 '14 at 09:13

1 Answers1

30

No, you cannot implement the CLR profiling APIs in managed code (C# or otherwise) since the profiling callbacks are called at very specific times when the managed environment is assumed to be in a certain state. Implementing your callbacks in managed code would violate a lot of assumptions.

David Broman, the developer of the CLR profiling APIs, has this to say:

You need to write your profiler in C++. The profiler is called by the runtime at very delicate points during execution of the profiled application, and it is often extremely unsafe to be running managed code at those points.

David's blog is a great resource for dealing with the CLR profiling APIs.

valiano
  • 16,433
  • 7
  • 64
  • 79
Chris Schmich
  • 29,128
  • 5
  • 77
  • 94
  • 3
    http://research.microsoft.com/en-us/um/redmond/projects/pex/wiki/Microsoft.ExtendedReflection.html – Karel Frajták Oct 03 '13 at 13:40
  • @KarelFrajták, are you saying that Pex counts as unmanaged code and can access the COM APIs, or is this link completely unrelated to this question? – NH. Oct 09 '17 at 16:54
  • 1
    I think there was an information on implementing the profiler methods in C# (it is not there anymore). But see http://www.jasonbock.net/News/Item/741d5181-6a06-4e7f-8a00-e03660dd16cf - quoting: "Pex is also interesting because of the technologies and frameworks that it uses that do all sorts of advanced, cool stuff. One, in particular, is called ExtendedReflection. This is basically a managed profiler - yes, you read that right. For the longest time, I was under the impression that you can't write a profiler in .NET in managed code, but I was wrong because ExtendedReflection does just that." – Karel Frajták Oct 14 '17 at 07:51