12

I like to understand how DllImport really works. I need a plain English explanation- meaning simple explanation.

Does it statically link with the exported method from the DLL, like an "include file" directive/static library?

Or does it dynamically call the method from the DLL when it gets to the execution point in the C# program?

Tom Silverman
  • 207
  • 3
  • 5

3 Answers3

25

It uses two core winapi functions. First is LoadLibrary(), the winapi function that loads a DLL into a process. It uses the name you specified for the DLL. Second is GetProcAddress(), the winapi function that returns the address of a function in a DLL. It uses the name of the function you specified. Then some plumbing runs that builds a stack frame for the function call, using the arguments you specified and it calls the function at the address it found.

So yes, this is very dynamic. This doesn't happen until your code actually lands on a statement that calls the pinvoked function. The technical term is "late binding" as opposed to the more common early binding used by the Windows loader for native code.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • 1
    It's quite amazing how much Win32 "lives on" in .NET...everything from bootstrapping the CLR with `LoadLibrary` on `mscoree.dll` to how p/invoke attaches to external libraries. Always know your roots! :) – JerKimball Jan 23 '13 at 17:48
  • Does this mean if I have two different versions of the same assembly I could call one version, swap the file and then again call the same method (those which are identical in both) without having any issues because it might use the wrong version resting in memory? I'm currently struggling with an implementation where we do need the old API for testing, but it won't be used for production purposes anymore. That way I could spare a lot of duplicate code. – SharpShade Feb 02 '18 at 12:41
8

It dynamically calls it. DLLimport does not embed anything in your compiled program. That is why when you use DLLImport it is important to make sure that the end user has the right DLL's in the right location, or your program will not work.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
FrostyFire
  • 3,212
  • 3
  • 29
  • 53
2

The latter - you can convince yourself of that by specifying a non-existing dll name. You'll be able to compile and run just fine but not call the function, of course.