[英]Calling thread with char pointer function and std::string produces different results
我有一個函數返回一個稱為loop_p
的char指針,並在main_thread
上多次調用它,將其傳遞給py_embed
線程:
HANDLE handle;
SENDTOPY *cmd=new SENDTOPY();
char* msg=loop_p(ac);
char *argv[4]={"PythonPlugIn2","bridge","test_callsign",msg};
cmd->argc=4;
for(int i = 0; i < NUM_ARGUMENTS; i++ )
{
cmd->argv[i] = argv[i];
}
handle=(HANDLE) _beginthread(py_embed,0,(void*)cmd);}
其中SENDTOPY
是結構:
typedef struct{
int argc;
char *argv[4];
}SENDTOPY;
像這樣發送給python和python的消息接收良好:
SENDTOPY *arg=(SENDTOPY*)data;
pArgs2=Py_BuildValue("(s)",arg->argv[4]);
pValue2 = PyObject_CallObject(pFunc, pArgs2);
為了避免出現內存分配問題,我將loop_p
函數修改為一個返回std::string
的函數。 然后,我通過一些修改在main_thread
調用該字符串:
...
std::string msg_python=loop_p(ac);
const char * msg2=msg_python.data();
char *argv[3]={"PythonPlugIn2","bridge","test_callsign"};
cmd->argc=3;
cmd->msg=msg2;
for(...
...
我將SENDTOPY
結構修改為:
typedef struct{
int argc;
char *argv[3];
const char* msg;
}SENDTOPY;
我將其打印到main_thread
的文本文件中,修改前后的消息相同。 但是在py_embed
線程中,const char不再是原來的,只是一堆亂碼。 我究竟做錯了什么?
先感謝您。
編輯: loop_p代碼
std::string CNewDisplay::loop_p(int ac){
std::string res("Number of Aircrafts\nHour of simulation\n\n");
for (...
....
//Route
textfile<<fp.GetRoute()<<endl;
std::string route=fp.GetRoute();
std::replace(route.begin(),route.end(),' ',',');
res+=route;
res.append(",\n");
res.append("\n\n");
};
return res;
}
在我看來,您正在存儲一個指向在堆棧上創建的臨時字符串對象的內部膽量的指針。 如果將字符串設為靜態,則字符串的膽量將在整個程序執行期間保持有效,並且可以安全地存儲指向字符串膽量的指針:
static std::string msg_python; // survives beyond local scope
msg_python=loop_p(ac); // set string to loop_p return value
const char *msg2=msg_python.c_str(); // get ptr each time since it could change
另外,請確保使用.c_str()獲取c樣式的char字符串指針,以確保該字符串以null終止。 使用.data()不能保證終止為空。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.