[英]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.