Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use DllImport Attribute as apposed to adding a reference?

I've seen a couple of examples such as this:

[DllImport("user32.dll")]
static extern bool TranslateMessage([In] ref Message lpMsg);

[DllImport("user32.dll")]
static extern IntPtr DispatchMessage([In] ref Message lpmsg);

But, what I don't understand is why someone would do that as apposed to just referencing the DLL like they do other libraries? The MSDN states: "The DllImport attribute is very useful when reusing existing unmanaged code in a managed application. For instance, your managed application might need to make calls to the unmanaged WIN32 API." But, is that saying it is not useful to reference an unmanaged dll or impossible otherwise?

like image 821
myermian Avatar asked Jul 23 '10 20:07

myermian


2 Answers

"But, is that saying it is not useful to reference an unmanaged dll or impossible otherwise?"

Yes, exactly so. What you're thinking of as 'referencing a DLL' is actually 'referencing a .NET assembly' - it just so happens that the most common way of packaging the kind of assemblies one tends to reference is in a DLL.

DLLImport is entirely about importing 'traditional DLLs' - i.e. ones which export all their methods using the original Windows DLL export mechanism.

Think of DLLImport as actually being called 'UnmanagedImport', and things might be clearer.

like image 188
Will Dean Avatar answered Nov 14 '22 00:11

Will Dean


Some libraries such as user32.dll are unmanaged code. Basically this means they do not have the required metadata to allow .Net to talk to them by reference (there is much more that goes into it but hopefully that gives you enough of a head start.)

  • Using the DllImport Attribute
  • DllImportAttribute
  • Win32/COM
  • PInvoke.Net <= more information about other unmanaged libraries for Windows
  • Managed vs. Unmanaged Development
like image 16
Matthew Whited Avatar answered Nov 14 '22 02:11

Matthew Whited