DLLs and Stacks

Unlike a task module, a DLL module does not have its own stack. Instead, it uses the stack segment of the task that called the DLL. This can create problems when a DLL calls a function that assumes the DS register and the SS register hold the same address. This problem is most likely to occur in small- and medium-model DLLs, since pointers in these models are, by default, near pointers.

Many C run-time library routines, for example, assume that DS and SS are equal. You must take care when you call these functions from within your DLL.

Your DLL can also encounter difficulties when calling user-written functions. Consider, for example, a DLL that contains a function that declares a variable within the body of the function. The address of this function will be relative to the stack of the task which called the DLL. If this function passes that variable to a second function that expects a near pointer, the second function will assume that the address it receives is relative to the DLL's data segment rather than to the stack segment of the task which called the DLL.

The following code fragment shows a function in a DLL passing a variable from the stack, rather than from its data segment:

void DLLFunction(WORD wMyWord)

WORD myWord

{

char szMyString[10];

.

.

.

AnotherFunction(szMyString);

}

If AnotherFunction was declared as accepting a near pointer to a character array (char NEAR *), it will interpret the address it receives as being an offset of the data segment, rather than of the stack segment of the task that called the DLL.

When you specify the code is to be built as a DLL, the compiler sets an option that ensures your DLL does not attempt to pass stack variables to functions that expect near pointers. This will produce warning messages that indicate when the DLL is making a call to a function that assumes that DS and SS are equal. When you receive a warning for a particular function, you can either remove that function call from your DLL, or rewrite the DLL source module so that it does not pass a stack variable to that function.