简体   繁体   中英

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

I have a function that returns a char pointer called loop_p and I call it many times on my main_thread like this to pass it to the py_embed thread:

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);}

where SENDTOPY is a struct:

typedef struct{
    int argc;
    char *argv[4];
}SENDTOPY;

The message it sent to python like this and python receives it well:

SENDTOPY *arg=(SENDTOPY*)data;
pArgs2=Py_BuildValue("(s)",arg->argv[4]);
pValue2 = PyObject_CallObject(pFunc, pArgs2);

In order to avoid having memory allocation problems i modified the loop_p function to a function that returns a std::string . I then call that string in the main_thread with some modifications:

...

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(...
 ...

and i modify the struct SENDTOPY to this:

typedef struct{
    int argc;
    char *argv[3];
        const char* msg;
}SENDTOPY;

I print it to a textfile in the main_thread and the message before and after the modifications are equal. But in the py_embed thread the const char is no longer what is was, is just a bunch of gibberish. What am I doing wrong?

Thank you in advance.

Edit: loop_p code

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;

}

It appears to me that you are storing a pointer to the internal guts of a temporary string object created on the stack. If you make string static, then the string's guts will remain valid throughout program execution, and you can safely store pointer to string guts:

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

Also, ensure that you use .c_str() to get your c-style char string pointer so that you are assured the string is null-terminated. Using .data() does not guarantee null termination.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM