#include <stdio.h>
#include <string.h>
typedef struct {
char * first_name;
char * last_name;
} selName;
static char name_buf[128];
static char command_result[128];
int add(int a, int b) {
printf("adding: [%d, %d]\n", a, b);
return b-a;
}
int multiple(int a, int b) {
printf("multi: [%d, %d]\n", a, b);
return b*a;
}
char * echo(selName * name) {
printf("echo: [%s, %s]\n", name->first_name, name->last_name);
memset(name_buf, 0, 128);
sprintf(name_buf, "%s %s", name->first_name, name->last_name);
return name_buf;
}
void * passthrough(int a, int b)
{
void (*fn)() = (void (*)()) add;
void *record = __builtin_apply_args();
int args[128];
args[0] = a;
args[1] = b;
int *p = (int*)record;
int *p1 = (int*) p[0];
int *p2 = (int*) p[0];
printf("params: [%d, %d]\n", p[0], p[1]);
void * playback = __builtin_apply( (void (*)(...))fn, record, 128);
p = (int*)playback;
p1 = (int*) p[0];
printf("params: [%d]\n", p[0]);
//printf("after calling [%d, %d]\n", (int)playback, *((int*)playback));
//__builtin_return(playback);
return playback;
}
void * callFunc(void * args, void * fn)
{
void * playback = __builtin_apply( (void (*)(...))fn, args, 128);
int * p = (int*)playback;
int * p1 = (int*) p[0];
printf("params: [%d]\n", p[0]);
//__builtin_return(playback);
return playback;
}
char * handleCommand(char * command)
{
static int arg_buf[128];
static int* arg_obj[1];
arg_obj[0] = (int*) arg_buf;
void * result;
void * args = &arg_obj;
if (strncmp(command, "add", 3) == 0) {
int a;
int b;
sscanf(command, "add %d %d", &a, &b);
arg_buf[0] = a;
arg_buf[1] = b;
void (*fn)() = (void (*)()) add;
void *result = callFunc((void*)args, (void*)fn);
memset(command_result, 0, 128);
int * p = (int*)result;
sprintf(command_result, "%d", p[0]);
}
else if (strncmp(command, "mul", 3) == 0) {
int a;
int b;
sscanf(command, "mul %d %d", &a, &b);
arg_buf[0] = a;
arg_buf[1] = b;
void (*fn)() = (void (*)()) multiple;
void *result = callFunc((void*)args, (void*)fn);
memset(command_result, 0, 128);
int * p = (int*)result;
sprintf(command_result, "%d", p[0]);
}
else if (strncmp(command, "echo", 4) == 0) {
selName tmp;
char first_name[16];
char last_name[16];
memset(first_name, 0, 16);
memset(last_name, 0, 16);
strncpy(first_name, command+5, 5);
strncpy(last_name, command+11, 2);
printf("param: %s %s", first_name, last_name);
tmp.first_name = first_name;
tmp.last_name = last_name;
arg_buf[0] = (int) &tmp;
void (*fn)() = (void (*)()) echo;
void *result = callFunc((void*)args, (void*)fn);
memset(command_result, 0, 128);
char ** p = (char**)result;
char *res = *p;
sprintf(command_result, "%s", res);
}
return command_result;
}
int main()
{
// void * p = passthrough(12, 23);
// printf("value: %d\n", *((int*)p));
char * res = handleCommand("add 3 5");
printf("result: [%s]\n", res);
res = handleCommand("echo harry he");
printf("result: [%s]\n", res);
}
|
|
|
|
|