3

I am developing a .NET library which is so far 100% managed. Now I need to use some win32 calls.

All I need to know is when is a .NET library called unmanaged? when the assembly has unmanaged code or when the unmanaged code in the assembly gets executed?

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
Santhanam
  • 166
  • 1
  • 7
  • 2
    I wouldn't get too hung up on nomenclature, personally - but: if you're calling out to unmanaged code (with the exception of the BCL which provides a contracted level of abstraction), you can't really call it 100% managed. – Marc Gravell Nov 12 '12 at 10:41
  • look at it this way: no matter what functionality you use in .net - sooner or later it will end up calling a win32 function - just make sure to clean up every external resource you used and don't think to much about the naming issue (BTW: I don't get it: why is this important?) – Random Dev Nov 12 '12 at 10:42
  • Possible duplicate http://stackoverflow.com/questions/334326/what-is-managed-unmanaged-code-in-c – tempidope Nov 12 '12 at 10:49

2 Answers2

2

As long as your code properly cleans up after making these unmanaged win32 calls, then your library will be managed.

Dave New
  • 38,496
  • 59
  • 215
  • 394
2

You think you're writing 100% managed code, but actually if you delve into the bowels of the .NET framework, even that calls unmanaged code. Try using ILSpy or .NET Reflector to find DllImport or extern method calls. The assembly itself is managed because .NET is doing all the JITing, security, garbage collection ect. to the objects in the assembly. At the point that .NET calls an unmanaged function (Win32 etc), .NET no longer has control over the code, therefore this is unmanaged!

It is good practice to learn how to "manage" unmanaged code imports. You should wrap interoperable calls so that .NET can clean up as much as possible once the interoperable call is complete.

Take a look here for information on how Platform Invoking should be used:

http://msdn.microsoft.com/en-us/library/aa288468%28v=vs.71%29.aspx

Matthew Layton
  • 39,871
  • 52
  • 185
  • 313