How can I support both Unicode and Multi-Byte Character Set in Static library (.lib)?

I am using visual studio 2015 and I want to write a C ++ static library that I can use in Unicode projects and in projects with several bytes, how do I do it right?

For example, I have this code:

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);
    }
}
+4
source share
2 answers

As Raymond Chen said in a comment, you can use two separate overloaded functions: one for Ansi, one for 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);
    }
}

Or, as rubenvb suggested, just forget about the Ansi function in general, focus only on 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);
    }
}
+1
source

, , Win32:

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

Source: https://habr.com/ru/post/1655955/


All Articles