views:

640

answers:

2

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.

+4  A: 

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.

anon
+4  A: 

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 :)

Benoit
"Why are you not simply using malloc/free directly?"- because using 'free' in one DLL on memory 'malloced' in a different DLL most often causes crashing.
Michal Czardybon
I fail to see how providing a level of indirection would fix that, unless you have your own memory management. I haven't run across issues of crash when malloc/free from different DLLs as long as you don't do a double free.
Benoit
http://msdn.microsoft.com/en-us/library/ms235460.aspxThe additional level of indirection provides access to single, shared (between all dlls) functions for memory management.
Michal Czardybon