Calling functions in C....

Bill Poser poser at csli.Stanford.EDU
Tue Aug 15 18:52:55 AEST 1989


In article <2108 at infmx.UUCP> segel at infmx.UUCP (Mike Segel) writes:

>	I want to write a C function which will be passed a set of strings.
>The C function would then use the first parameter as the function name,
>and the other parameters as the variables. 
>	I can figure out how to get the variables passed, but I cannot
>think of a way to handle the function name.
>

If I understand the problem correctly, what is desired is to map strings
to function addresses. To do this, set up a data structure whose elements
are structures containing the function name and its address, e.g.:

	struct foo {
		char *name;		/* Name of function as string */
		int (*func)();		/* Pointer to function */
	};

If you use an array, the declaration and initialization would look like
this:

	struct foo funcmap[]={
		"function1",function1,
		"function2",function2,
		....
		"functionN",functionN
	};

Then define an access function that searches the data structure, using the
function name, and returns the pointer to the matching function (i.e.
funcmap[i].func) which you then execute via the pointer, e.g. like this:

	funcptr = LookupFunction(string);
	if(funcptr != NULL) retval = (*funcptr)(arg1,arg2,...argn);
	
The nature of the data structure and the corresponding access function
depend on the properties of the function list and how fast the search needs
to be. The easiest thing to do is to create an array of structs and use
linear search. If you know the names of all the functions at compile time
and can make sure they are correctly ordered you can do binary search
instead.  In some circumstances a hashing technique will be appropriate.



More information about the Comp.lang.c mailing list