使用 char 指针函数和 std::string 调用线程会产生不同的结果

Calling thread with char pointer function and std::string produces different results

本文关键字:结果 线程 调用 指针 char 函数 string std 使用      更新时间:2023-10-16

我有一个函数,它返回一个名为 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() 并不能保证空终止。