mercredi 26 septembre 2018

How to execute common code before and after another function in c?

here I explain the problem. Suppose I have a struct A loaded in shared memory. The struct A might be something like this:

typedef enum{
    GPIO_1,
    GPIO_2,
    GPIO_3,
    GPIO_4,
    GPIO_5,
    N_GPIO
} gpio;

struct B {
    bool active;
    bool status;
    bool direction;
    int timestamp;
    int t1;
    int t2;
};

struct A {
    struct B gpio[N_GPIO];
};

Also suppose I have two functions which would operate on one of the B structs in A:

bool set_status(gpio g, bool status, int t1, int t2);
bool activate(gpio g, bool active);

Since A is loaded in shared memory, I need to call shmget and shmdt within the two functions above; the pseudocode for the first function should be something like this:

bool set_status(gpio g, bool status, int t1, int t2) {
    struct A shm = shmget();
    struct B target = shm.gpio[g];
    if(target.active) {
        bool res = foo1(target, status, t1, t2); //do something on struct B indexed by g
        shmdt();
        return res;
    else 
        return false;
}

The pseudocode for the second function should be something like this:

bool activate(gpio g, bool active) {
    struct A shm = shmget();
    struct B target = shm.gpio[g];
    if(target.active) {
        bool res = foo2(target, active); //do something on struct B indexed by g
        shmdt();
        return res;
    else
        return false;
}

Now, is there a way I can prevent to have that common code which manages shm and checks if B.active is set? To me, this looks something like decorators, i.e. have a function that manages shm, checks for B.active and calls a second function within it, but the problem is that that the second function might has not a unique signature (might have different number of parameters).

Thanks!

Aucun commentaire:

Enregistrer un commentaire