The actual project often encountered many similar operations, such as command code corresponding to the execution function, for such operations, the better way is to use the const array, the command code and operation functions are bound together, by looking up the table to find the operation function, and execute the operation function. This simplifies the code, reduces complexity, and is well implemented in C, which can be a bit cumbersome in C + +.
As an example of serial-port command parsing, first define a struct that defines the type of pointer to an operation function:
struct t_shellinfo{ string cmd; void (* dealfunc) (const vector<string> &vectstr); string desc;};
Defines the command resolution execution class, which is defined as static and defines a const static array:
classcshell{ Public: Cshell (); ~Cshell (); voidrecvcmd ();Private: enum{shell_info_num_max=Ten}; voidGetcmd (Const Char*CMDSTR, vector<string> &vectstr); voidDeal (Constvector<string> &vectstr); Static voidCmdhelp (Constvector<string> &vectstr); Static voidCmdled (Constvector<string> &vectstr); Static voidCmdtask (Constvector<string> &vectstr); Static voidCmddisk (Constvector<string> &vectstr); Static voidCmdtime (Constvector<string> &vectstr); Static voidCmdreboot (Constvector<string> &vectstr);Cshell*_self; Const Statict_shellinfo _shellinfo[shell_info_num_max];};
When implemented, initializes the array first
ConstT_shellinfo cshell::_shellinfo[shell_info_num_max]={ {"?", Cmdhelp,"Show All cmd"}, {" Help", Cmdhelp,"Show All cmd"}, {" Time", Cmdtime,"Show Sys time"}, {"Task", Cmdtask,"Show all Task info"}, {"Disk", Cmddisk,"disk cmd [info ls, cat rm format]"}, {"led", cmdled,"set led [normal charge alarm]"}, {"reboot", Cmdreboot,"reboot SYS"}, {""Null""}};
Once the serial port receives the command, it simply iterates through the array, finds the execution function of the same command code and executes it.
voidCshell::D EAL (Constvector<string> &vectstr) { for(U8 i =0; i< Shell_info_num_max; i++) { if(_shellinfo[i].cmd.length () = =0) { Break; } if(_shellinfo[i].cmd = = vectstr[0]) {_shellinfo[i]. Dealfunc (VECTSTR); return; }} printf ("cmd \ "%s\" err!\r\n", vectstr[0].c_str ());}
Then implement the corresponding operation function one by one:
voidCshell::cmdtask (Constvector<string> &vectstr) {U8 pcwritebuffer[ -]={0}; //U8 *pcwritebuffer = new u8[500];//This value should be careful, too small to cause an array overflow, too general to cause a stack overflowprintf"=================================================\r\n"); printf ("Task Name task status priority remaining stack task ordinal \ r \ n"); Vtasklist ((Char*) &Pcwritebuffer); printf ("%s\r\n", Pcwritebuffer); //delete[] Pcwritebuffer;}
Definition and initialization method of member function pointer array in C + +