Is the DllImport attribute always an unmanaged DLL loaded

This question inspired me to ask the following question. Does the DllImport attribute always load a specific DLL, even if you do not call / use this method.

For example, if you have the following code:

static class Program { [DllImport("kernel32.dll")] static extern bool AllocConsole(); static void Main() { if (true) { //do some things, for example starting the service. } else { AllocConsole(); } } } 

Now that the application is running, AllocConsole will never be launched, but will the dll be loaded anyway?

+6
source share
2 answers

As MSDN says:

Search and loading of the DLL, and the location of the address of the function in memory occurs only when the function is first called.

But you can easily verify this by specifying a nonexistent dll in the attribute.

+4
source

I did a little test. The following program works fine:

 static class Program { [DllImport("doesnotexist.dll")] static extern bool AllocConsole(); static void Main() { if (false) AllocConsole(); } } 

The following program throws a DllNotFoundException on the AllocConsole () line.

 static class Program { [DllImport("doesnotexist.dll")] static extern bool AllocConsole(); static void Main() { if (true) AllocConsole(); } } 

So it looks like the dll only loads on the first call.

+3
source

Source: https://habr.com/ru/post/906930/


All Articles