[comp.lang.c] Building function call at runtime

stumpf@gtenmc.UUCP (Jon S. Stumpf) (12/11/89)

I have a list of variables of unknown type on an application stack.
On top of the list are static variables, such as a format string and
the number of variables in the list.  I have access to this application
stack only through type dependent functions, such as pop_int() and
push_double().

	-------------------	What I want to do is pop the variables
	|  Format String  |	off the stack and make a call to an
	-------------------	error routine passing a format string
	|   List Length   |	and the list.  The error routine
	-------------------	would be implemented using <varargs.h>
	|   List Elem n   |	stuff (<stdargs.h> is not available, yet).
	-------------------
	|                 |	Assume a routine called popper() is
	|       ...       |	responsible for popping the information
	|                 |	off the stack, doing whatever, and calling
	-------------------	the print (error) routine.
	|   List Elem 1   |
	-------------------	Assume a routine called error() is
	|   Other Stuff   |	responsible for printing a meaningful
	-------------------	error message using a format string,
	|                 |	list of arguments, and some global
	V                 V	information.


I want to keep the error routine simple and use <varargs.h> and do the
work in the intermediate popper() function.  I believe the main question
is:

	How do I get the variables off the application stack and
	onto the runtime stack so error() can use <varargs.h> ?


I have thought of one workaround.  The popper() routine could parse the
format string, calling fprintf() for all non-expansion strings (%).
When an expansion string is encountered:

	- I determine the type of the variable on the stack
	  so I can pop using the appropriate function.

	- Call fprintf() using the expansion string as the format
	  string and the popped value as the third argument.

I understand that I have to handle the fact that the list is in reverse
order.

This workaround is obviously not the only solution nor the nicest.  It
also merges the popper() routine and error() routine.  Something I don't
want to do.

Any suggestions?
-- 
 jss - Jon S. Stumpf

tps@chem.ucsd.edu (Tom Stockfisch) (12/11/89)

In article <307@gtenmc.UUCP> stumpf@gtenmc.UUCP (Jon S. Stumpf) writes:
>	How do I get the variables off the application stack and
>	onto the runtime stack so error() can use <varargs.h> ?

Use vfprintf(), which takes a varargs list as an argument:

static void
error(ap)
	va_list	ap;
{
	FILE	*fp;
	char	*format;

	fp =		va_arg( ap, FILE * );
	format =	va_arg( ap, char * );
	vfprintf( fp, format, ap );
	handleError();
}
-- 

|| Tom Stockfisch, UCSD Chemistry	tps@chem.ucsd.edu