问题:如何使用 string/char* 变量作为 GetPrivateProfileInt 方法的路径参数。
我正在尝试使用 GetPrivateProfileInt给 window 。以下代码运行完美,没有任何问题:
int x = GetPrivateProfileInt(L"x",L"y",1,L"This\\is\\the\\path");
但在我的例子中,路径被传递给了函数。像这样:
void fun(std::string path)
{
//error const char* is incampatible with LPCWSTR.
int x = GetPrivateProfileInt(L"x",L"y",1,path.c_str());
}
在下面给出的一些尝试中,x 正在接收默认值。即路径未正确传递给 GetPrivateProfileInt 方法。
以下是我的其他几个尝试:
尝试 1:
// No error, default value is being read.
int x = GetPrivateProfileInt(L"x",L"y",1,(LPCTSTR)path.c_str());
尝试 2:
// No error, default value is being read.
int x = GetPrivateProfileInt(L"x",L"y",1,(wchar_t*)path.c_str());
尝试 3:
//_T() macro giving error.
// 'Ls' : undeclared identifier.identifier "Ls" is undefined.
LPCTSTR path_s = _T(path.c_str());
int x = GetPrivateProfileInt(L"x",L"y",1,path_s);
我查看了答案 here但无法找到解决方案。
最佳答案
该函数有两种版本,一种采用 UCS-2 字符 (GetPrivateProfileIntW
),另一种采用 char
字符 (GetPrivateProfileIntA
)。没有允许您混合参数的版本。您的选择是将 appname 和 keyname 参数更改为单字节以匹配您的数据
GetPrivateProfileIntA("x", "y", 1, path.c_str());
或使用 MultibyteToWideChar
将最后一个参数转换为 UCS-2,然后调用 GetPrivateProfileIntW
。
指针转换不是字符编码的转换,不会起作用。编译器类型系统可以帮助您,用强制转换关闭它几乎总是错误的做法(异常(exception):GetProcAddress
的返回值确实需要强制转换)。
关于c++ - GetPrivateProfileInt 方法的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40981792/