无法从'std :: string'转换为'LPSTR'

Sim*_*ons 20 c++ windows

由于我不能将LPCSTR从一个函数传递到另一个函数(数据被更改),我尝试将其作为字符串传递.

但后来我需要再次将其转换回LPSTR.在尝试转换时,我收到上述错误:

无法从'std :: string'转换为'LPSTR'

我该如何解决这个问题?

Key*_*lug 26

那只是因为你应该使用std::string::c_str()方法.

但这涉及const_cast给定的情况,因为const char *返回的c_str()不能分配给非常量LPSTR.

std::string str = "something";
LPSTR s = const_cast<char *>(str.c_str());
Run Code Online (Sandbox Code Playgroud)

但是你必须确保它的寿命str会比LPTSTR变量的寿命长.

另一个提及,如果代码编译为符合Unicode,那么类型LPTSTRstd::string不兼容.你应该使用std::wstring.

重要说明:如果将结果指针s从上面传递给试图修改数据的函数,则指向此函数将导致未定义的行为.正确处理它的唯一方法是将字符串复制到非const缓冲区(例如via strdup)


Ped*_*ino 7

如果您需要LPSTR,这意味着将修改字符串.std::string::c_str()返回一个const指针,你不能只是const_cast它离开并希望世界上一切都好,因为它不是.字符串可能会以各种令人讨厌的方式改变,而您的原始字符std::string将无视所有字符串.

试试这个:

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

将字符串包裹在智能指针中并摆脱try...catch奖励积分(不要忘记自定义删除器).