无法从“ std :: string”转换为“ LPSTR” [英] cannot convert from 'std::string' to 'LPSTR'
问题描述
由于我无法将LPCSTR从一个函数传递给另一个函数(数据已更改),因此我尝试将其作为字符串传递。
As I clould not pass LPCSTR from one function to another (Data get changed) I tried passing it as a string.
但是稍后我需要再次将其转换回到LPSTR。尝试进行转换时,出现上述错误:
But later I need to again convert it back to LPSTR. While trying the conversion I am getting the above error:
无法从'std :: string'转换为'LPSTR'
cannot convert from 'std::string' to 'LPSTR'
我该如何解决?
推荐答案
那只是因为您应该使用 std :: string :: c_str ()
方法。
That's just because you should use std::string::c_str()
method.
但这在特定情况下涉及 const_cast
因为 c_str()
返回的 const char *
不能分配给非常量 LPSTR
。
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());
但是您必须确保 str
将比 LPTSTR
变量更长。
But you must be sure that lifetime of str
will be longer that that of LPTSTR
variable.
再说一遍,如果代码编译为符合Unicode的代码,则 LPTSTR
和 std :: string
类型不兼容。您应该改用 std :: wstring
。
Another mention, if code compiles as Unicode-conformant, then types LPTSTR
and std::string
are incompatible. You should use std::wstring
instead.
重要说明:如果通过结果指针 s
从上面指向试图修改其指向的数据的函数将导致不确定的行为。正确处理它的唯一方法是将字符串复制到非常量缓冲区中(例如,通过 strdup
)
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
)
这篇关于无法从“ std :: string”转换为“ LPSTR”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!