Difference between dllimport and getProcAddress

First, I know that it makes no sense to compare the dllimport attribute and the getProcAddress function directly. Rather, I'm interested in comparing two pieces of code that basically implement the same thing - calling a function in dll - by importing a function with the dllimport attribute or using the getProcAddress function. In particular, I am writing a C # application that uses some function in a DLL that I wrote. First, I accessed my dll function with the following code snippet:

class DllAccess { [DllImport("kernel32.dll", SetLastError = true)] private extern IntPtr LoadLibrary(String DllName); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate Bool BarType(Byte arg); // return value indicates whether function call went well or not. Bool Bar(Byte arg) { Bool ok = false; IntPtr pDll= LoadLibrary("foo.dll"); if (pDll != IntPtr.Zero) { IntPtr pfunc = GetProcAddress(pDll, "bar"); if (pFunc != IntPtr.Zero) { BarType bar = (BarType)Marshal.GetDelegateForFunctionPointer(pFunc, typeof(BarType)); ok = bar(arg); } FreeLibrary(pDll); } return ok; } } 

However, later I needed to get the lastError value if it was set during the dll call, so I changed the code to this:

 class DllAccess { [DllImport("foo.dll", EntryPoint = "bar", CallingConvention = CallingConvention.StdCall, SetLastError = true)] private extern Bool DllBar(Byte arg); // return value indicates whether function call went well or not. Bool Bar(Byte arg) { return DllBar(arg); } } 

This, of course, is much more neat, and, as already mentioned, it sets the lastError code. Obviously, my first code snippet gives me the ability to change the dll and function call at runtime, but this is not required at the moment. So my question is: is there any reason to use the first wording if I'm sure that I will not use another dll or another function?

+3
source share
2 answers

The only real benefits of using GetProcAddress are that you can unload the DLL manually as well as call the function, and that you can easily change the naming at runtime.

However, the second option provides you with a huge number of advantages. In addition to being β€œtidier,” it also handles most of the data type marshaling for you, which becomes very important with some APIs.

However, if you follow the first method that you specified first, you must also unload everything. Right now, you basically skip addresses every time you call Bar () ... For more, see FreeLibrary .

+4
source

Probably the biggest advantage of GetProcAddress is that it allows you to control the search path in the DLL. For example, you can automatically download the 32-bit or 64-bit version of the embedded DLL. With DllImportAttribute this is not possible.

+2
source

All Articles