c++ - 如何在我的命名空间中使用 LoadString 宏?

标签 c++ visual-studio winapi namespaces macros

当我在命名空间中使用 LoadString WinAPI 宏时,我遇到了问题。我的功能:

namespace Bushman {
    // Get the string from the resource's string table of the module.
    // I use the same name like WinAPI macros but with own signature.
    PTSTR LoadString(HMODULE h, DWORD id) {
        h = NULL == h ? ::GetModuleHandle(NULL) : h;
        PTSTR ptr = NULL;
        // it returns really length instead of concatenated 
        // string length, therefore I can use it for malloc.
        int i = ::LoadString(h, id, (PTSTR)&ptr, 0);
        if (0 == i) {
            return NULL;
        }
        PTSTR string = (PTSTR)malloc(i * (sizeof(TCHAR) + 1));
        ::LoadString(h, id, string, i + 1);
        return string; // NOTE: don't forget free resource in the outer code.
    }
}

我得到编译错误:

'LoadStringW': is not a member of 'Bushman'
'LoadStringW': is not a member of 'Bushman'
'LoadStringW': is not a member of 'Bushman'

我该如何解决?

UPD

我认为问题是宏有这样的定义

#ifdef UNICODE
#define LoadString  LoadStringW
#else
#define LoadString  LoadStringA
#endif // !UNICODE

而不是像这样:

#ifdef UNICODE
#define LoadString  ::LoadStringW
#else
#define LoadString  ::LoadStringA
#endif // !UNICODE

UPD 2

我找到了问题的原因。问题出在我的代码的其他地方。我在我的代码中使用了这样的声明:

namespace Bushman {} // namespace declaration
PTSTR Bushman::LoadString(HMODULE h, DWORD id); // function declaration

但这是错误的。如果我将其重写为:

namespace Bushman {
    PTSTR LoadString(HMODULE h, DWORD id);
}

最佳答案

您有几个选择:

  1. 不要包含定义 LoadString 宏的 Windows 头文件,或者
  2. 包含该头文件,但使用 #undef 取消定义宏。

这个问题确实没有很好的解决方案。一旦你开始使用宏,你就失去了轻松隔离和控制它们影响的能力。预处理器不关心您的 namespace 。


关于你对问题的更新,你并没有真正解决问题。从 UPD2 中的代码开始,预处理器将 LoadString 转换为 LoadStringW。您只是没有意识到这一点,因为它在编译过程中透明地发生。但是,如果您尝试从另一个未定义 LoadString 宏的翻译单元使用您的类,您会发现该函数名为 LoadStringW

关于c++ - 如何在我的命名空间中使用 LoadString 宏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33277639/

相关文章:

c++ - 子类化 EDIT 控件

c++ - std::map 中的最后一个键

c - 将 WINAPI 函数指针存储在结构体中

c++ - 写入和读取opencv3.0 ml文件(随机森林)

c++ - 调试器如何只看到值而不是变量的内存地址

visual-studio - 在 Docker 容器中运行时的 .NET Core 分析

c++ - 这些链接器错误的含义是什么?

c++ - 如何从另一个进程中解开全局钩子(Hook)?

C++ 入门第 5 版 : Difference between the deleter of a shared_ptr and of unique_ptr's

c++ - 如何在 Linux C++ 中使用字符串到字符串 hash_map(hash_map<string, string, stringHashFunction>