command liste

Gast #365629
Lesenswert?
• ▲
▼
baue mir gerade eine kleine shell über die UART. Ich hab schon oft sowas
gemacht aber sonst immer die commandliste von hand gebaut mit switch und
so, geht, find ich aber irgendwie hässlich! Das ganze kann man ja auch
universeller machen. ich sehe das oft mal da wird dann eine liste
gebaut wie:
(pseudocode)
cmdlist = { "setup", setup_func, .... } usw.

wenn ich jetzt durch diese liste durchloopen würde, dann immer den
commandkey ("setup") mit der eingabe vergleiche wie würde ich dann
klarmachen, dass setup_func eine funktion ist die dann aufgerufen
werden soll? Hat jemand ne idee? danke :)
Gast #365630
Lesenswert?
• ▲
▼
Du definierst das Element als Funktionszeiger. Vielleicht hilft
folgendes:
1
struct cmd
2
{
3
    const char* name,
4
    void (*func)(void);
5
};
6

7
struct cmd cmdlist[] =
8
{
9
    { "setup", setup_func},
10
    { 0, 0}
11
};
12

13
...
14

15
int execute(const char* command)
16
{
17
    for (cmd* c = cmdlist; cmd->name != 0; ++cmd)
18
    {
19
        if (strcmp(cmd->name, command))
20
        {
21
            cmd->func();
22
            return 1;
23
        }
24
    }
25
    printf("Unknown command\n");
26
    return 0;
27
}

Wenn du noch Parameter übergeben willst, mußt du dir halt überlegen,
wie du das einbaust.
Gast #365635
Lesenswert?
• ▲
▼
so hab glaub ich alle gefunden :p

struct cmd
{
  const char* name;
  void (*func)(void);
};

void poll()
{
  float val = ((float)ADC/1024.0f)*5.0f;
  char string[10];
  dtostrf(val,5,1,string);
  printf("Polling.....\nADC: %sV\n",string);
}


struct cmd cmdlist[] =
{
  { "poll", poll },
  { 0, 0 }
};


int execute(const char* command)
{
  struct cmd *c = 0;
  for (c = cmdlist; c->name != 0; ++c) {
    if (!strcmp(c->name, command)) {
      c->func();
      return 1;
    }
  }
  printf("Unknown command\n");
  return 0;
}

Antwort schreiben

Bitte melde dich an, um einen Beitrag zu schreiben.

oder

Mit Google-Account einloggen

Die Registrierung ist kostenlos und dauert nur eine Minute.

Jetzt registrieren