使用 char 指针函数和 std::string 调用线程会产生不同的结果
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 AircraftsnHour of simulationnn");
for (...
....
//Route
textfile<<fp.GetRoute()<<endl;
std::string route=fp.GetRoute();
std::replace(route.begin(),route.end(),' ',',');
res+=route;
res.append(",n");
res.append("nn");
};
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 样式的字符字符串指针,以便确保字符串以 null 结尾。使用 .data() 并不能保证空终止。
相关文章:
- QtConcurrent - 在发布到 UI 线程的数千个结果中保持 GUI 响应
- C++ 多线程给出不同的结果
- C++ 线程端回调并返回结果
- 在向量上声明缩减,在 1 个线程上运行给出的结果与没有 openmp 的结果不同
- 错误 C2064:term 的计算结果不是采用 1 个参数的函数 - 关于线程的一些东西
- 提升线程:术语的计算结果不为 0 个参数
- 如何在C++中获取线程的结果
- 多线程合并选项的奇怪结果
- 多线程文件读取为每个线程生成相同的结果
- 在多线程工作负载上解释Gperftools的结果
- 从多个线程收集结果的缓存友好方式
- 将线程的结果转储到向量中是线程安全的吗
- 从 IOCP 线程调用 WSAGetLastError() 将返回不正确的结果
- 与单线程相比,c++/java的多线程性能结果参差不齐
- 如何从线程的结果返回Qt对象(Qtfutur)
- CUDA 线程在全局内存中的私有位置写入时出现错误结果
- 我的线程工作不好,它给出了所有结果,最后没有一个接一个,GUI 在线程运行期间挂起?
- 从非线程阻塞消息框获取结果
- 线程合并排序给出无效结果
- C++ 将结果从多个线程返回到数组中