[英]C++ program crashing on Python script call
我试图发送运行特定python脚本的命令:但是,只要程序到达执行行,就会发生这种情况:
GameServer.exe中0x69bd1f16处未处理的异常:0xC0000005:访问冲突读取位置0x46f520ca。
该程序停止共振并崩溃。 这是有问题的方法:
void ScriptManager::runScript(std::string scriptName, std::string args[])
{
std::string py = "python " + scriptName;
std::cout << py << std::endl;
for(int i = 0; i < args->length(); i++)
{
py += " " + args[i];
std::cout << py << std::endl;
}
std::cout << py << std::endl;
std::system(py.c_str());
}
这将调用上面的函数:
void DBFactory::dbRegisterUser(std::string username, std::string password)
{
ScriptManager script;
std::string data[] = {username, password};
script.runScript("Python.py", data);
}
据我所知,脚本无法运行。 如果有帮助,我也可以发布脚本。
这就是问题:
for (int i = 0; i < args->length(); i++)
{
py += " " + args[i];
std::cout << py << std::endl;
}
args->length()
等效于args[0].length()
; 也就是说,您要获取数组中第一个字符串的长度,并将其用作索引。 经过两次迭代后,您将访问数组末尾。 最好的解决方案是(所有示例都是未测试的):
使用std::array
(仅C ++ 11):
void DBFactory::dbRegisterUser(std::string username, std::string password) { ScriptManager script; script.runScript("Python.py", {username, password}); } void ScriptManager::runScript(std::string scriptName, std::array<std::string, 2> args) { std::string py = "python " + scriptName; std::cout << py << std::endl; for (std::string s : args) { py += " " + s; std::cout << py << std::endl; } std::cout << py << std::endl; std::system(py.c_str()); }
使用std::vector
(示例使用C ++ 03):
void DBFactory::dbRegisterUser(std::string username, std::string password) { ScriptManager script; int tmp[2] = {username, password}; script.runScript("Python.py", std::vector<std::string>(&tmp[0], &tmp[0]+2)); } void ScriptManager::runScript(std::string scriptName, std::vector<std::string> args) { std::string py = "python " + scriptName; std::cout << py << std::endl; for(std::vector<std::string>::iterator it = args.begin(); it != args.end(); it++) { py += " " + *it; std::cout << py << std::endl; } std::cout << py << std::endl; std::system(py.c_str()); }
传递数组大小作为参数:
void DBFactory::dbRegisterUser(std::string username, std::string password) { ScriptManager script; script.runScript("Python.py", {username, password}, 2); } void ScriptManager::runScript(std::string scriptName, std::string args[], int size) { std::string py = "python " + scriptName; std::cout << py << std::endl; for(int i=0; i<size; i++) { py += " " + args[i]; std::cout << py << std::endl; } std::cout << py << std::endl; std::system(py.c_str()); }
我个人更喜欢示例1,并且会像瘟疫一样避免使用示例3。 示例2运作良好,但可能不如示例1快。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.