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

前端 未结 6 2052
故里飘歌
故里飘歌 2020-12-09 16:12

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

相关标签:
6条回答
  • 2020-12-09 16:57

    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)

    0 讨论(0)
  • 2020-12-09 17:01

    An LPSTR can be substituted with by using a TCHAR (i.e. found in tchar.h). So if you have a std::string, you can use the method std::string::c_str().

    0 讨论(0)
  • 2020-12-09 17:02

    There is a function on std::string c_str() . However I doubt that you could not use a std::string in your case.

    0 讨论(0)
  • 2020-12-09 17:07

    If you need an LPSTR, that means the string will/may be modified. std::string::c_str() returns a const pointer, and you can't just const_cast it away and hope all is good in the world, because it isn't. The string may be changed in all sorts of nasty ways, and your original std::string will be oblivious to all of them.

    Try this instead:

    // myFunction takes an LPSTR
    std::string cppString = "something";
    LPSTR cString = strdup( cppString.c_str() );
    try {
       myFunction( cString );
       cppString = cString;
    } catch(...) {
       free( cString );
    }
    

    Wrap the string in a smart pointer and get rid of the try...catch for bonus points (don't forget the custom deleter).

    0 讨论(0)
  • 2020-12-09 17:11

    If the function, you are calling does not write to string, but only reads it, then you can simply use string::c_str method. If it is going to write something, then you probably should ensure that your string has enough space by calling string::reserve().

    0 讨论(0)
  • 2020-12-09 17:13

    Are you running somestringvariablename.c_str()? That should work.

    0 讨论(0)
提交回复
热议问题