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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With