Is it safe to pass function pointers as arguments to dll functions and invoke them from inside of the dll?

StackOverflow https://stackoverflow.com/questions/653697

Question

I would like to pass some (dll or not) function pointers as arguments to some dll functions and call them from inside of the dll. I wonder if it is safe because I have found an information on http://publib.boulder.ibm.com/infocenter/zos/v1r10/index.jsp?topic=/com.ibm.zos.r10.cbcpx01/fpref.htm that:

In DLL code, it is assumed that a function pointer points to a function descriptor. A function pointer call is made by first obtaining the function address through dereferencing the pointer; and then, branching to the function entry. When a non-DLL function pointer is passed to DLL code, it points directly to the function entry. An attempt to dereference through such a pointer produces an undefined function address. The subsequent branching to the undefined address may result in an exception.

Does this rule apply to Visual Studio and other compilers as well?

What precisely I am trying to do is to solve the problem of memory allocation and deallocation between various dll and non-dll functions. My idea is to pass two function pointers - for common allocation and deallocation functions - to every dll in some initialization (e.g. Initialize(&malloc, &free)) and then do all memory management using these common and thus always compatible functions.

Was it helpful?

Solution

It's not true. DLL code treats function pointers in exactly the same way as non-DLL code. If that were not the case, one could not use standard library functions like qsort() (which expects a function pointer argument) within a DLL.

OTHER TIPS

Passing function pointers to a DLL has been done for generations.

All the callback functions used in GUI programming (for example progress bars update) use function pointers.

When developing using WIN32, is there a reason you want to use function pointers to malloc/free? Why are you not simply using malloc/free directly?

That is how I have always done it in the past. Not that this guarantees it's the correct way.
In fact, you might take that as an indication that it's the worst possible way :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top