处于开发测试需要,经常需要在程序中内嵌一些特权指令,用于快速到达、获取、实现想要的功能或物品。但是这些指令只能在测试期间生效,不能在线上生效。
一般做法在于加上一个配置,用于标识release与debug环境。其次,根据不同权限可以实行不同级别的指令。所有的特权指令定义成为数组结构容器,容器中添加调用关键字、调用函数、权限、描述等等。
Gm GmCmds[] =
{
{"test-gm", Gm::my_print, Gm::MODE_SUPER, "测试指令"},
{ "test-gm-2", Gm::my_print_2, Gm::MODE_SUPER | Gm::MODE_GM | Gm::MODE_ROOT, "测试指令2" },
{NULL, NULL, 0, NULL},
};
如上图,定义Gm对象的数组,对象由四部分构成,关键字“test-gm”,函数名"Gm::my_print",权限"Gm::MODE_SUPER",描述"测试指令"。
头文件:
//GM测试
struct Gm
{
enum
{
MODE_FORMAL = 0,
MODE_GM = 1,
MODE_SUPER = 2,
MODE_ROOT = 4,
MODE_ALL = 7,
};
const char *pstCmd;
bool(*pstParse)(const char *pstPara);
int iPriv;
const char *pstDesc;
static bool exec(const char *pstCmd);
static bool my_print(const char *pstPara);
static bool my_print_2(const char *pstPara);
};
实现文件:
int iMyMode = Gm::MODE_FORMAL;
Gm GmCmds[] =
{
{"test-gm", Gm::my_print, Gm::MODE_SUPER, "测试指令"},
{ "test-gm-2", Gm::my_print_2, Gm::MODE_SUPER | Gm::MODE_GM | Gm::MODE_ROOT, "测试指令2" },
{NULL, NULL, 0, NULL},
};
bool Gm::exec(const char *pstCmd)
{
if (!pstCmd || strlen(pstCmd) <= 2)
return false;
if (pstCmd[0] == '/' && pstCmd[1] == '/')
{
std::string strParse = pstCmd + 2;
for (int i = 0; i >= 0; ++i)
{
if (!GmCmds[i].pstCmd) break;
if (strncmp(GmCmds[i].pstCmd, strParse.c_str(), strlen(GmCmds[i].pstCmd)) == 0)
{
if (0 == (iMyMode & GmCmds[i].iPriv))
{
cout << "权限不足" << endl;
break;
}
//cout << "exec already find" << endl;
return GmCmds[i].pstParse(strParse.c_str());
}
}
//cout << "exec no find" << endl;
}
return false;
}
bool Gm::my_print(const char *pstPara)
{
if (!pstPara)
return false;
cout << pstPara << endl;
return true;
}
bool Gm::my_print_2(const char *pstPara)
{
if (!pstPara)
return false;
cout << pstPara << endl;
return true;
}
int main()
{
Gm gm;
iMyMode |= Gm::MODE_GM;
char chTest[100] = "//test-gm";
if (!gm.exec(chTest))
{
cout << "other handle: " <<chTest << endl;
}
iMyMode |= Gm::MODE_ALL;
memset(chTest, 0, 100);
strncpy(chTest, "//test-gm-2" , sizeof("//test-gm-2"));
if (!gm.exec(chTest))
{
cout << "other handle: " << chTest << endl;
}
return 0;
}