Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does DllImport really work?

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?

like image 373
Tom Silverman Avatar asked Jan 23 '13 02:01

Tom Silverman


3 Answers

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.

like image 113
Hans Passant Avatar answered Oct 18 '22 07:10

Hans Passant


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.

like image 32
FrostyFire Avatar answered Oct 18 '22 07:10

FrostyFire


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.

like image 2
500 - Internal Server Error Avatar answered Oct 18 '22 06:10

500 - Internal Server Error