Functional design pointers

I have a problem with a design question in C.

Let's say that I have a fairly large number of functions with a different number of arguments.

POQ:

int print_one(int x)
{
    printf("one: %d\n", x);
    return 1;
}

int print_three(int x, int y, int z)
{
    printf("three: %d-%d-%d\n", x, y, z);
    return 3;
}

Now I want to associate some properties with these functions in the structure so that I can manipulate them without knowing the exact function, including their number of parameters (I could even name the interface of the structure)

I tried it like this: (& I think this is wrong):

typedef int (*pfunc)(int c, ...);

typedef struct _stroffunc
{
    pfunc myfunction;
    int flags;
    int some_thing_count;
    int arguments[10];
    int argumentcount;
} stroffunc;

int main()
{
    stroffunc firststruct;

    firststruct.pfunc = (pfunc) print_two;
    firststruct.something_count = 101;
    arguments[0] = 102;
    argumentcount = 1;
    flag &= SOME_SEXY_FLAG;

    // now I can call it, in a pretty ugly way ... however I want (with patially random results ofc)
    firststruct.pfunc(firststruct.arguments[0]);
    firststruct.pfunc(firststruct.arguments[0], 124, 11);
    firststruct.pfunc(1, firststruct.arguments[0], 124, 1, 1);
}

I find this solution very ugly, and I think (hopefully) that there is a better solution for calling and setting function pointers.

I just hope I was clear enough ... NOTE. I did not compile this code, but I compiled and ran very similar, so the concepts work. NOTE: pure C required

+3
source share
3

undefined . , (char int s ..), .

, . :

typedef struct {
    int num_args;
    union {
        void (*f1)(int);
        void (*f2)(int, int);
        void (*f3)(int, int, int);
    } func;
} magic;


...

magic m;
...
switch (m.num_args) {
case 1: m.func.f1(arg1); break;
case 2: m.func.f2(arg1, arg2); break;
case 3: m.func.f3(arg1, arg2, arg3); break;
default: assert(0);
}

- .

+1

, , - ABI.

. wikipedia

0

, , , , "" ,

int initFunc(int (*pfunc)(int c,...));

This function will save the pointer in the structure, as the context in POO, in the structure that you will use, as a “map” of the entire function a, which you will call each of them using the identifier.

which returns id and you store it in an array, then another func will say

int call(int id,int p1,...);

where you say the function identifier and parameters, make sure that you should now, which function is each id

0
source

All Articles