I have some straightforward C-style code that implements a simple command interpreter as follows:
typedef struct {
char *name;
int (*func)(char* args);
} sCOMMAND;
int func_reset(char* args);
int func_acc(char* args);
int func_dec(char* args);
const sCOMMAND CmdTbl[] = {
{ "RST", func_reset },
{ "ACC", func_acc },
{ "DEC", func_dec }
};
void ProcessCommand (char *cCmd)
{
int ndx = NUM_CMDS;
// shortest cmd is 3 chars
if (strlen(cCmd) >= MIN_CMD_LEN)
{
/////////////////////////////////////////////////////
// Chop the command line into substrings with ptr to
// each one where *parm[0] points to the command.
char *parms[MAX_PARMS];
ParseCommand(cCmd, parms);
/////////////////////////////////////////////////////
// Scan the command table looking for a match
for (int ndx = 0; ndx < NUM_CMDS; ndx++)
{
if (stricmp (CmdTbl[ndx].name, &parms[0]) == 0)
{
// command found, run its function
CmdTbl[ndx].func(parms);
}
}
}
// no valid command was found
if (ndx == NUM_CMDS)
Serial.println("UNKNOWN COMMAND");
Serial.println("RDY> ");
}
This works, but what I'd like to do is encapsulate the command interpreter in a C++ class. But I haven't been able to get the sCOMMAND table set up with class methods. My recent attempt is:
// in file CmdHandler.h
class CmdHandler;
typedef struct {
char *name;
int (CmdHandler::*func)(char* args);
} sCOMMAND;
class CmdHandler
{
public:
CmdHandler(int buf_size);
~CmdHandler(void) { if (m_Buf) delete [] m_Buf; };
void ProcessCommand (char *cCmd);
private:
char *m_Buf;
int m_BufSize;
char *parms[MAX_PARMS];
void ParseCommand(char *cCmd, char* (&parms)[MAX_PARMS]);
int func_1(char* args);
int func_2(char* args);
int func_3(char* args);
sCOMMAND CmdTbl[3];
};
// in file CmdHandler.cpp
#include "CmdHandler.h"
CmdHandler::CmdHandler(int buf_size)
: CmdTbl{ {"RST", func_1},
{"ACC", func_2},
{"DEC", func_3} }
{
m_BufSize = buf_size;
m_Buf = new char[m_BufSize];
}
void CmdHandler::ProcessCommand (char *cCmd)
{
}
On ARM GCC CPP Compiler, this gives an error "cannot convert 'CmdHandler::func_1' from type 'int (CmdHandler::)(char*)' to type 'int (CmdHandler::*)(char*)'".
If I take the pointer reference out of the struct as:
typedef struct {
char *name;
int (CmdHandler::func)(char* args);
} sCOMMAND;
I get
"CmdHandler.h: invalid use of incomplete type 'class CmdHandler'
int (CmdHandler::func)(char* args);".
Can anyone tell me how to solve this, or suggest any better way?