GetPrivateProfileInt 方法的参数

Parameters of GetPrivateProfileInt method

问题:如何使用string/char*变量作为GetPrivateProfileInt方法的路径参数。

我正在尝试使用为 windows 提供的 GetPrivateProfileInt。以下代码运行完美,没有任何问题:

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)。没有允许您混合参数的版本。您的选择是将 appnamekeyname 参数更改为单字节以匹配您的数据

GetPrivateProfileIntA("x", "y", 1, path.c_str());

或使用 MultibyteToWideChar 将最后一个参数转换为 UCS-2,然后调用 GetPrivateProfileIntW

指针转换不是字符编码的转换,不会起作用。编译器类型系统可以帮助你,用强制转换关闭它几乎总是错误的做法(例外:GetProcAddress 的 return 值确实需要强制转换)。