如何在命名空间中使用LoadString宏?

时间:2015-10-22 09:26:19

标签: 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':不是'Bushman'的成员
''LoadStringW':不是   'Bushman'的成员
''LoadStringW':不属于   '布什曼'

我该如何解决?

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 个答案:

答案 0 :(得分:2)

您有以下几种选择:

  1. 不要包含定义LoadString宏的Windows头文件,或
  2. 包含该头文件,但使用#undef取消定义宏。
  3. 这个问题确实没有很好的解决方案。一旦开始使用宏,您就会失去容易隔离和控制其影响的能力。预处理器不关心您的命名空间。

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