Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

c++ - cannot convert from 'std::string' to 'LPSTR'

As I clould not pass LPCSTR from one function to another (Data get changed) I tried passing it as a string.

But later I need to again convert it back to LPSTR. While trying the conversion I am getting the above error:

cannot convert from 'std::string' to 'LPSTR'

How can I resolve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

That's just because you should use std::string::c_str() method.

But this involves const_cast in given case because const char * returned by c_str() can not be assigned to a non-constant LPSTR.

std::string str = "something";
LPSTR s = const_cast<char *>(str.c_str());

But you must be sure that lifetime of str will be longer that that of LPTSTR variable.

Another mention, if code compiles as Unicode-conformant, then types LPTSTR and std::string are incompatible. You should use std::wstring instead.

Important note: If you pass the resulting pointer s from above to a function which tries to modify the data it is pointing to this will result in undefined behaviour. The only way to properly deal with it is to duplicate the string into a non-const buffer (e.g. via strdup)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...