【问题标题】:How can i suppport both Unicode and Multi-Byte Character Set in Static library (.lib)?如何在静态库 (.lib) 中同时支持 Unicode 和多字节字符集?
【发布时间】:2016-09-27 10:44:07
【问题描述】:

我正在使用 Visual Studio 2015,我想编写可以在 Unicode 项目和多字节项目中使用的 C++ 静态库,我是如何做到的?

例如我有这个代码:

namespace Reg
{
    LONG WINAPI CreateKey(
        _In_  HKEY    hKey,
        _In_  LPCTSTR lpSubKey,
        _In_  REGSAM  samDesired,
        _Out_ PHKEY   phkResult
        )
    {
        return RegCreateKeyEx(hKey,
            lpSubKey,
            0, NULL,
            REG_OPTION_NON_VOLATILE,
            samDesired,
            NULL,
            phkResult,
            NULL);
    }
}

【问题讨论】:

  • 只用一个wchar_t接口,不用管所有的TCHAR业务。发明时是个坏主意,现在也是个坏主意。在任何情况下,不使用“宽”版本的 Windows API 都是愚蠢的。
  • 你必须有两个函数,因为这是C++,你可以重载,所以有两个CreateKey函数,一个接受LPCWSTR,一个接受LPCSTR。跨度>
  • @RaymondChen 我可以只有一个带有LPCTSTR 和两个定义的声明,一个带有LPCWSTR 和一个带有LPCSTR 的定义吗?
  • @codeDom:不。每个函数都需要自己的声明和定义。
  • @RaymondChen 我尝试使用单一声明进行编译,并且成功。这是什么意思?

标签: c++ visual-studio unicode multibyte


【解决方案1】:

就像 Raymond Chen 在评论中建议的那样,您可以使用两个单独的重载函数 - 一个用于 Ansi,一个用于 Unicode:

namespace Reg
{
    LONG WINAPI CreateKey(
        _In_  HKEY    hKey,
        _In_  LPCSTR  lpSubKey,
        _In_  REGSAM  samDesired,
        _Out_ PHKEY   phkResult
        )
    {
        return RegCreateKeyExA(hKey,
            lpSubKey,
            0, NULL,
            REG_OPTION_NON_VOLATILE,
            samDesired,
            NULL,
            phkResult,
            NULL);
    }

    LONG WINAPI CreateKey(
        _In_  HKEY    hKey,
        _In_  LPCWSTR lpSubKey,
        _In_  REGSAM  samDesired,
        _Out_ PHKEY   phkResult
        )
    {
        return RegCreateKeyExW(hKey,
            lpSubKey,
            0, NULL,
            REG_OPTION_NON_VOLATILE,
            samDesired,
            NULL,
            phkResult,
            NULL);
    }
}

或者,就像 rubenvb 建议的那样,完全忘记 Ansi 函数,只关注 Unicode 本身:

namespace Reg
{
    LONG WINAPI CreateKey(
        _In_  HKEY    hKey,
        _In_  LPCWSTR lpSubKey,
        _In_  REGSAM  samDesired,
        _Out_ PHKEY   phkResult
        )
    {
        return RegCreateKeyExW(hKey,
            lpSubKey,
            0, NULL,
            REG_OPTION_NON_VOLATILE,
            samDesired,
            NULL,
            phkResult,
            NULL);
    }
}

【讨论】:

    【解决方案2】:

    您可以按照通常用于 Win32 函数的方式进行操作:

    CreateKeyW(..)  { unicode implementation }
    CreateKeyA(..) { byte string implementation }
    #ifdef UNICODE
    #define CreateKey CreateKeyW
    #else
    #define CreateKey CreateKeyA
    #endif
    

    【讨论】:

    • 我会使用 C++ 函数重载而不是 C 宏。 Win32 API 中的那些#define 语句会导致 3rd 方库中的各种问题,因此最好避免在您自己的代码中导致同样的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多