wasAsked.

What is unmanaged code? Why is it called "unmanaged"? Give some examples.

Routeware · Role not specified · technical

Published

Year not specified · Software Engineering

Community answers

Posted by wasAsked editorial collection

Unmanaged code is code that runs outside the control of the .NET runtime (the Common Language Runtime, CLR). It is called "unmanaged" because the CLR does not manage its memory, type safety, exceptions or security — the code (or the developer) manages them directly. Managed vs unmanaged Managed code (C#, F#, VB.NET compiled to IL): - Executed by the CLR with JIT or AOT compilation. - Memory is allocated on the managed heap and freed automatically by the garbage collector. - Type safety checks, bounds checking on arrays, structured exception handling and security features. Unmanaged code: - Compiled directly to machine code (for example C or C++ native libraries) and executed by the OS. - Memory is allocated and freed manually (malloc and free, new and delete); mistakes cause leaks, buffer overflows and crashes. - No garbage collection or runtime type verification. Examples - Windows API functions in kernel32.dll and user32.dll. - Native C or C++ libraries: image processing libraries, SQLite's native engine, OpenSSL, device drivers, graphics libraries. - COM components (such as older Office automation objects). - Operating system resources accessed through handles: file handles, sockets, window handles, database connection handles in native drivers. How .NET interacts with unmanaged code 1. P/Invoke (Platform Invocation): [LibraryImport("user32.dll", StringMarshalling = StringMarshalling.Utf16)] private static partial int MessageBoxW(IntPtr hWnd, string text, string caption, uint type); (DllImport is the older attribute; LibraryImport uses source generation in .NET 7+.) 2. COM interop through runtime callable wrappers. 3. C++/CLI (Windows) as a bridge layer. 4. unsafe code in C# with pointers (still managed code, but bypassing safety checks). Why it matters for developers - Resources obtained from unmanaged code are not released by the garbage collector. Wrap them in classes implementing IDisposable, ideally using SafeHandle so the handle is released reliably, and call Dispose (via using). - Marshalling data between managed and unmanaged memory has a cost; minimise transitions in hot paths. - Bugs in unmanaged code can crash the whole process, bypassing .NET exception handling. Many .NET classes wrap unmanaged resources internally — FileStream, SqlConnection, Socket, Bitmap — which is why they implement IDisposable.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics