Reputation: 1907
I register functions at a global registry. A function can have multiple arguments. I can register and call them from the registry. Here is one of my unit tests to understand the registry.
void *a_test_function_d(int a, char *b){
printf("*** c_test called\n");
isRunD = a;
testChar = b;
return NULL;
}
TEST(testWithMultibleArguments) {
isRunD = 0;
testChar = "";
add_command(a_test_function_d);
assertEquals(1, avl_tree_count(command_registry));
exec_command("a_test_function_d", 42, "test");
assertEquals(42, isRunD);
assertEquals("test", testChar);
avl_tree_free(command_registry);
command_registry = NULL;
}
This works fine for me so far. But here comes the part I can’t find a nice solution for. From a line-parser i get tokens. The first one should be the command, the following tokens are the arguments. If i would have a fixed length of arguments, than i doesn’t have any problems, but how can I construct a function or a macro that handles a variable count of tokens to pass them as arguments to a function?
This is what i have so far:
// split lines into tokens
char *token;
token = strtok(linebuffer," ");
if (token) {
if ( has_cammand(token) ) {
// HOW TO PUT ARGS from strtok(linebuffer," ") to FUNCTION....
exec_command(token /* , a1, a2, a3 */ );
} else {
uart_puts("Command not found.\n");
}
}
My line buffer is a char* and can look like:
find honigkuchen
set name peter
(coming from a user input interactive shell).
the prototypes of the functions would be:
void *find(char *);
void *set(char *, char *);
Of cause I can define a macro and count _VA_ARGS_
, or the array and do a if-else on 1, 2, 3, 4, … Parameters, but this seems a bit messy to me.
There must be a better way to convert a array, to a parameter list.
Upvotes: 0
Views: 118
Reputation: 16143
Pass the array and the number of items in the array as arguments to the function under test. Is there some reason to complicate this further?
Keep in mind that an array passed to a function is really a pointer to the first item in the array.
So, if you have:
// Prototype for test function:
bool testFunction( char *items, int itemCount );
char items[10];
int itemCount = 0;
// Get items from where ever
items[0] = 'a';
items[1] = 'r';
items[2] = 'r';
items[3] = 'a';
items[4] = 'y';
itemCount = 5;
// Assume testFunction returns true if the test succeeds, else false
if( testFunction( items /*or &items[0] to make it more clear*/, itemCount ) )
puts( "Success!" );
else
puts( "Failure :(" );
Ask away if anything is unclear...
Upvotes: 1