简体   繁体   中英

how to store pointer to function that takes arguments in Fsm?

I want to implement a function with arguments in FSM . when I try this, this error appears

error: initializer element is not constant
         {(&DriveCenter)(86),50,{stop,right,left,stop}},
 note: (near initialization for 'fsm[0].fun')
 error: initializer element is not constant
{(&DriveRight)(45),50,{stop,right,left,stop}},

Here is the code:

void DriveCenter(unsigned long out){
    printf("\ncenter = %d",out);
}

typedef struct  {
    void (*fun)(unsigned long out);
    unsigned long delay;
    unsigned long Next_State[4];
} state ;


state fsm[4] ={
        {(&DriveCenter)(86),50,{stop,right,left,stop}},
        {(&DriveRight)(45),50,{stop,right,left,stop}},
        {(&DriveLeft)(787),50,{stop,right,left,stop}},
        {(&DriveStop)(33),50,{stop,right,left,stop}}
};

You can not set a parameter when initializing a pointer to function, the parameter should be declared as another member of the struct

typedef struct  {
    void (*fun)(unsigned long);
    unsigned long out;
    unsigned long delay;
    unsigned long Next_State[4];
} state ;

state fsm[4] = {
    {DriveCenter,86,50,{stop,right,left,stop}},
    {DriveRight,45,50,{stop,right,left,stop}},
    {DriveLeft,787,50,{stop,right,left,stop}},
    {DriveStop,33,50,{stop,right,left,stop}}
};

Under C11 you can use anonymous struct s to clarify that these two variables work together:

typedef struct  {
    struct {
        void (*fun)(unsigned long);
        unsigned long out;
    };
    unsigned long delay;
    unsigned long Next_State[4];
} state ;

state fsm[4] = {
    {{DriveCenter,86},50,{stop,right,left,stop}},
    {{DriveRight,45},50,{stop,right,left,stop}},
    {{DriveLeft,787},50,{stop,right,left,stop}},
    {{DriveStop,33},50,{stop,right,left,stop}}
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM