C++ 如何在名称空间中使用LoadString宏?
当我在命名空间中使用C++ 如何在名称空间中使用LoadString宏?,c++,visual-studio,winapi,namespaces,macros,C++,Visual Studio,Winapi,Namespaces,Macros,当我在命名空间中使用LoadStringWinAPI宏时,它有一个问题。我的职能: 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) {
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);
}
您有以下几种选择:
LoadString
宏的Windows头文件,或#undef
取消定义宏关于你对问题的更新,你还没有真正解决问题。从UPD2中的代码开始,预处理器将
LoadString
转换为LoadStringW
。您只是没有意识到这一点,因为它在编译过程中是透明的。但是,如果您尝试从另一个未定义LoadString
宏的翻译单元使用您的类,您会发现该函数名为LoadStringW
谢谢。我在我的主题中添加了UPD。我认为这不会改变我所说的任何事情。您包括了一个定义宏的卡车负载的单元。这些就是结果。@DavidHeffernan-会“3.更改自定义LoadString
方法的名称,这样它就不会与原来的方法冲突,也不会被替换。”这也是一个很好的建议吗?@b可能。这是一个很大的限制。我更喜欢将windows头文件的用户隔离为封装任何功能的低级代码。从根本上说,尽管Windows头文件依赖于宏,但没有很好的解决方案。David,我添加了UPD 2.:)谢谢你的帮助。所以错误信息是准确的,额外的W只是一个错误的线索。这种情况经常发生。