tags:

views:

281

answers:

4

Wonder what the difference between:

static PROCESSWALK pProcess32First=(PROCESSWALK)GetProcAddress(hKernel,"Process32First");
...
pProcess32First(...);

and

#include <Tlhelp32.h>
...
Process32First(...);

What are the differences, I wonder which I should use. Is there any difference in terms of best practices then?

+5  A: 

NOTE: my answer assumes that the function is available either way, there are other things to consider if you are after non-exported functions.

If you use LoadLibrary and GetProcAddress, then you have the option running with reduced functionality if the required library isn't there. if you use the include and link directly the lib, and dll isn't there (or doesn't have the export due to wrong version) your app will simply fail to load.

It really only makes a difference if you want to use a function that isn't in all versions of a given dll.

Evan Teran
+2  A: 

See here for Microsoft's explanation.

Implicit linking (using *.lib) is simplier.

As for kernel libraries, there are no other difference.

Quassnoi
+2  A: 

I would take the first approach if I had optional plugin libraries that the user may or may not have. For necessary libraries I would use the second since it is a lot less code to get the functions.

Fredrik Jansson
+2  A: 

In addition to what Evan said (which is correct), another important difference (IMHO) is that if you're dynamically loading functions, you need to have a typedef to cast the void* to in order to call the function once it's loaded. Unless the header files which defines the function prototype for static linkage has a mechanism for also defining the typedef for the function pointer from the same template function definition code, you're going to end up with a duplicate function definition, probably in your code. If the external header definitions are ever updated (for example, with new definitions for 64bit data types), you risk runtime errors in your application unless you update the other function prototypes (these will not be caught at compile time, because of the c-style cast to the function typedef).

It's a subtle issue, but an important one to consider. I would use implicit ("static") linking if you can because of that issue, and if you're using dynamic loading, be aware of the issue, and structure your code to avoid problems in the future as best you can.

Nick