我有这个函数返回一个字符串:
string getStringFromFile()
{
ifstream in("in.txt");
ofstream out("out.txt");
std::string line;
while(getline(in,line)){
if(line.empty())
line="http://www.google.com/";
}
return line;
}
Run Code Online (Sandbox Code Playgroud)
尝试调用该getStringFromFile函数时,它返回语法错误(Error : identificator not defined).
CreateWindowEx(0, _T("EDIT"),
_T(getStringFromFile()),
WS_CHILD | WS_VISIBLE | WS_BORDER,
260, 10,
200, 20,
hWnd, NULL, hInst, NULL);
Run Code Online (Sandbox Code Playgroud)
你不能这样使用_T().它是一个将L后缀应用于字符串文字的宏,而不是可以应用于任意表达式的函数.
您应该从这些库类型的宽字符串版本开始,这基本上等同于您尝试使用以下内容进行攻击_T():
std::wifstreamstd::wofstreamstd::wstring当您调用Windows API函数时,您似乎也必须获取指向字符串数据的指针,而不是尝试传递实际的C++字符串对象.
getStringFromFile().c_str()这会给你wchar_t const*你需要的东西,说实话,我不完全确定用一个临时的方法来做这件事是否安全.这取决于前提条件CreateWindowEx.
最安全的方法,IMO:
std::wstring getStringFromFile()
{
std::wifstream in("in.txt");
std::wofstream out("out.txt");
std::wstring line;
while (std::getline(in,line)) {
if (line.empty())
line = "http://www.google.com/";
}
return line;
}
// ...
const std::wstring str = getStringFromFile();
CreateWindowEx(0, _T("EDIT"),
str.c_str(),
WS_CHILD | WS_VISIBLE | WS_BORDER,
260, 10,
200, 20,
hWnd, NULL, hInst, NULL
);
Run Code Online (Sandbox Code Playgroud)
作为进一步的复杂性,_T()宏只L在程序UNICODE定义时将后缀应用于字符串文字.如果您希望同时支持Unicode和非Unicode模式,则在未定义std::string时,您需要切换回原始模式UNICODE.话虽这么说,但我一直认为UNICODE现在很少发生致残.不过,我不是Windows开发者......