c++ - GetPrivateProfileInt 方法的参数

标签 c++ windows visual-studio ini

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

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

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

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

关于c++ - GetPrivateProfileInt 方法的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40981792/

相关文章:

windows - 使用 SSH 在 Windows 中远程调用显示桌面

C: 如何查看电脑是否被锁定/休眠?

c# - 如何将 .NET 库的源代码获取到 VS

c++ - 为什么 VC++ IntelliSense 不刷新错误列表?

c++ - 关于函数引用和线程的问题

c++ - 可以在 taskkill 命令期间调用 atexit() 吗?

C++:关于加载DLL和调用函数的一件小事

windows - 如何使用性能计数器监视 WCF 服务的正常运行时间?

visual-studio - 无需外部可执行文件的 VS 2010 构建操作

c++ - 将指向虚拟成员函数的指针作为参数传递给普通 C 函数