views:

261

answers:

4

Frequently when I am using the Reflector, I come across lots of unsafe code. Anyone knows how much of .NET is unmanaged/safe?

A: 

It doesn't really matter as the unsafe calls are wrapped by the corresponding .NET objects. What you need to be concerned about is resource allocation and disposing of objects that implement IDisposable.

Ed Swangren
+6  A: 

There are many instances of PInvoke that just call Win32 APIs. However, there is some functionality that is implemented in the CLR itself (e.g. Interlocked operations). If you want to see how this is done, look at Rotor.

I go into a detailed explanation of locking (viewing the Rotor source) in this post on my blog.

To specifically answer your question, you'd have to get all the .NET source code (e.g. use NetMassDownloader and grep for lines that say "InternalCall" or "DllImport") and compare that with the count of all lines. Perhaps you could multiply each of these "unmanaged" lines by some factor to guess, or you'd have to dive into Rotor or the Windows source code to get the actual numbers. If you went this far then things will get fuzzy (e.g. if File.Open calls Win32's CreateFile, then should CreateFile be counted towards .NET? I think not). So, at best you'd only multiply the "InternalCall"s by some factor to guess.

Jeff Moser
NetMD is pretty interesting.
Joan Venge
+1  A: 

Much of System.Windows.Forms calls into the unmanaged windows API, but I have not found the need to manually dispose of objects I create in this namespace.

When using the System.IO.FileStream class (also calls into unmanaged code), make sure you call Dispose when you are done so you can guarantee the file gets closed right there and then instead of when the finalizer executes.

John JJ Curtis
There is a reason that an object implements IDisposable. You may not see a problem, but you probably have a memory leak if you are not disposing of the objects,
Ed Swangren
+6  A: 

This is a really difficult question to answer. Unsafe code is easy to quantify in the sense that it exists in the binary and can be measured in terms of IL instructions.

Real unmanaged code, say PInvoke or COM, do have code in the binary but it is insignificant. It represents only the minimal stub necessary to call into the native function. This means you can't really measure how much native code is being excercised in a managed DLL. All you can do is measure the number of calls which provides no real measure of how much unmanaged code is executing.

JaredPar