7

What is the difference between the usages of DllImport here? Specifically, does "user32" just mean "user32.dll", or does it mean "user32.lib" or something else?

[DllImport("user32")]
protected static extern int GetKeyboardState(byte[] pbKeyState);

[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
protected static extern short GetKeyState(int vKey);

You can probably ignore the CharSet and CallingConvention.

If they are the same, I can rewrite this to be more consistent, but if not, I don't want to have a bunch of problems with it.

Kendall Frey
  • 43,130
  • 20
  • 110
  • 148
  • [Here is the MSDN page on the constructor](http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.dllimportattribute.dllimportattribute.aspx) for reference. – Guvante Mar 05 '12 at 22:28
  • The relevant documentation is that for [LoadLibrary](http://msdn.microsoft.com/en-us/library/windows/desktop/ms684175(v=vs.85).aspx). *If the string specifies a module name without a path and the file name extension is omitted, the function appends the default library extension .dll to the module name. To prevent the function from appending .dll to the module name, include a trailing point character (.) in the module name string.* – David Heffernan Mar 06 '12 at 18:51

2 Answers2

13

In this example, there is no difference. The .dll extension will automatically be appended to "user32" to create "user32.dll". However, this is not always the case. If the library file name contains a period, the .dll extension will not be automatically appended.

Some examples:

[DllImport("user32")] --> Resolves "User32.dll". Correct.

[DllImport("user32.dll")] --> Resolves "User32.dll". Correct.

[DllImport("mylib.version5")] --> Resolves "mylib.version5". Incorrect

[DllImport("mylib.version5.dll")] --> Resolves "mylib.version5.dll". Correct.

ahawker
  • 3,306
  • 24
  • 23
  • Seems that in the Mono implementation of .NET, periods in the library name do not prevent automatic appending of extensions. (At least in the version of Mono used in Unity 4.5.1, which I believe is a variant of Mono 3.0.) – yoyo Sep 10 '14 at 00:55
  • +1 for the "period in library file name", been scratching my head for hours about that one (which is rather obvious now). – helmesjo Aug 08 '16 at 21:19
1

On Windows there is no difference, the import will be performed successfully if you omit the extension. Normally omitting the extension is desired when running Mono with the <dllmap> configuration section, where the P/Invoke runtime will look for aliases.

kprobst
  • 16,165
  • 5
  • 32
  • 53