Microsoft MVP성태의 닷넷 이야기
C/C++: 184. C++ - ICU dll을 이용하는 예제 코드 (Windows) [링크 복사], [링크+제목 복사],
조회: 5388
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일

(시리즈 글이 5개 있습니다.)
오류 유형: 848. .NET Core/5+ - Process terminated. Couldn't find a valid ICU package installed on the system
; https://www.sysnet.pe.kr/2/0/13266

닷넷: 2153. C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법
; https://www.sysnet.pe.kr/2/0/13430

C/C++: 184. C++ - ICU dll을 이용하는 예제 코드 (Windows)
; https://www.sysnet.pe.kr/2/0/13796

C/C++: 185. C++ - 문자열의 대소문자를 변환하는 transform + std::tolower/toupper 방식의 문제점
; https://www.sysnet.pe.kr/2/0/13797

닷넷: 2308. C# - ICU 라이브러리를 활용한 문자열의 대소문자 변환
; https://www.sysnet.pe.kr/2/0/13800




C++ - ICU dll을 이용하는 예제 코드 (Windows)

(이 글에 포함된 일부 유니코드 문자는 모바일 웹 브라우저에서는 정상적으로 안 보일 수 있습니다.)




예전에, (지원은) 닷넷 5부터 ICU dll을 사용한다고 했는데요,

C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법
; https://www.sysnet.pe.kr/2/0/13430

C++에서는 어떻게 사용하는지 잠깐 살펴보겠습니다. 일단, 윈도우의 경우 해당 라이브러리가 준비돼 있어야 할 텐데 vcpkg를 이용하는 경우 빌드는 쉽게 완료할 수 있습니다.

그리고 사용법마저도, 검색해 보니 githu에 있군요. ^^

c-icu-tolower-toupper / main.c
; https://github.com/RicardasSim/c-icu-tolower-toupper/blob/master/main.c

위의 소스코드를 "C++ - 윈도우에서 한글(및 유니코드)을 포함한 콘솔 프로그램을 컴파일 및 실행하는 방법" 글에서 설명한 방법으로 변환한 다음의 기본 예제로 시작해 보겠습니다.

#pragma execution_character_set( "utf-8" )

#include <iostream>

// ICU dll을 위한 기본 헤더 파일
#include <unicode/utypes.h>
#include <unicode/ucnv.h>
#include <unicode/ustring.h>
#include <unicode/ustdio.h>

#include <Windows.h>

int main()
{
    SetConsoleOutputCP(65001);

    char testStr[] = "\xf0\x90\xb2\x80"; // U+10C80 코드(OLD HUNGARIAN CAPITAL LETTER)
    std::cout << testStr << std::endl; // 출력 결과: 𐲀


    return 0;
}

그럼, 저 testStr에 있는 utf-8 인코딩된 문자열을 ICU 라이브러리를 사용해 utf-16 인코딩하는 것을 이렇게 작성할 수 있습니다.

char testStr[] = "\xf0\x90\xb2\x80";
std::cout << testStr << std::endl;

UErrorCode errorCode = U_ZERO_ERROR;
int32_t length;
int32_t retLength;
UChar* uStr;

{
    // 우선, utf-16 인코딩 결과물을 위해 필요한 버퍼 크기를 알아냄.

    u_strFromUTF8(NULL, 0, &length, testStr, -1, &errorCode);
    if (errorCode != U_ZERO_ERROR && errorCode != U_BUFFER_OVERFLOW_ERROR)
    {
        printf("Error: (ICU) %s\n", u_errorName(errorCode));
        return 1;
    }

    errorCode = U_ZERO_ERROR;

    if (length < 1)
    {
        printf("Error: the length less than 1.\n");
        return 1;
    }

    // UChar == char16_t
    // UTF-16 (2바이트) 인코딩에 필요한 바이트 수 + 1(널 문자) 만큼 할당.
    uStr = (UChar*)malloc((length + 1) * sizeof(UChar));
    if (!uStr)
    {
        printf("Error: unable to allocate memory (1).\n");
        return 1;
    }
}

{
    // utf-8 문자열을 utf-16 문자열로 변환.
    u_strFromUTF8(uStr, length + 1, &retLength, testStr, -1, &errorCode);

    // utf-16 인코딩 문자열이므로 Windows의 경우 W 버전의 API를 사용해 출력 가능
    WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), uStr, retLength, NULL, NULL);
    printf("\n");

    free(uStr);
}

소스코드가 에러 처리로 인해 길어졌지만, 전체적인 방식은 Windows에서도 MultiByteToWideChar 등의 인코딩 변환 함수를 사용하는 절차와 비슷합니다.

또한, github 원문 소스에서는 저렇게 변환한 utf-16 문자열을 화면에 출력하기 위해 printU 함수로 전달하는데요, printU 함수는 내부적으로 다시 utf-16 인코딩 문자열을 u_strToUTF8 함수를 이용해 utf-8로 변환 후 출력하는 역할만 합니다. 따라서, Windows 환경이라면 그런 변환 필요 없이 WriteConsoleW를 호출해도 됩니다.

그나저나 2개의 함수 이름을 보면,

  • u_strFromUTF8
  • u_strToUTF8

이제 작명 규칙이 눈에 보이는데요, 즉 icu 라이브러리에서의 "u_str"은 "UTF-16 문자열"을 의미합니다.




그다음 알아볼 것은 소문자로 변환하는 방법인데요, 이것도 위의 u_strFromUTF8 함수를 사용하는 것과 절차는 비슷합니다. 다만 호출하는 함수가 u_strToLower라는 것이 다른데요, 이름에서 알 수 있듯 이것은 "UTF-16" 문자열(u_str)을 대상으로 소문자로 변환(ToLower)하는 함수입니다.

따라서, 소스코드에서 utf-8 문자열을 사용하고 있다면 u_strFromUTF8 함수를 사용해 utf-16 문자열로 변환한 다음에 u_strToLower 함수를 호출해야 합니다.

혹은, Visual C++의 wchar_t 타입인 경우라면 그냥 곧바로 u_strToLower를 호출해도 되는데요, 아래는 그 예제를 보여줍니다.

UChar* lowerStr;
wchar_t pText[] = L"\xD803\xDC80";
UChar* uText;

{
    // 우선, 소문자로 변환했을 때의 결과물을 위해 필요한 버퍼 크기를 알아냄.
    uText = (UChar*)pText;

    length = u_strToLower(NULL, 0, uText, -1, nullptr, &errorCode);

    if (errorCode != U_ZERO_ERROR && errorCode != U_BUFFER_OVERFLOW_ERROR)
    {
        printf("Error: (ICU) %s\n", u_errorName(errorCode));
        return 1;
    }

    errorCode = U_ZERO_ERROR;

    if (length < 1)
    {
        printf("Error: length less than 1.\n");
        return 1;
    }

    // UTF-16 (2바이트) 소문자 텍스트가 보관될 버퍼 할당
    lowerStr = (UChar*)malloc((length + 1) * sizeof(UChar));
    if (!lowerStr)
    {
        printf("Error: unable to allocate memory (2).\n");
        return 1;
    }
}

{
    // UTF-16 문자열의 소문자 변환
    retLength = u_strToLower(lowerStr, length + 1, uText, -1, nullptr, &errorCode);

    if (errorCode != U_ZERO_ERROR)
    {
        printf("Error: (ICU) %s\n", u_errorName(errorCode));
        free(lowerStr);
        return 1;
    }

    WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), lowerStr, retLength, NULL, NULL);

    free(lowerStr);
}

딱히 더 설명할 필요가 없군요, ^^ 그리고 출력 결과는 '𐲀' 문자의 소문자에 해당하는 '𐳀' 문자가 나옵니다. (U+10CC0(OLD HUNGARIAN SMALL LETTER A))

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




예제의 나머지는 대문자로 변환하는 것인데요, 방식은 u_strToUpper 함수만 사용한다는 차이를 제외하고는 소문자를 변환할 때와 정확하게 같으므로 생략하겠습니다. ^^

그리고 아래의 예제 코드는 "c-icu-tolower-toupper / main.c" 파일을 Visual C++에서 약간의 컴파일 오류가 발생하는 것을 수정해 본 것입니다.

#include <iostream>

#include <unicode/utypes.h>
#include <unicode/ucnv.h>
#include <unicode/ustring.h>
#include <unicode/ustdio.h>

/*
--------------------
 printU();
--------------------
*/

bool printU(UChar* str)
{

    int32_t len;
    UErrorCode errorCode = U_ZERO_ERROR;
    char* s;

    u_strToUTF8(NULL, 0, &len, str, -1, &errorCode);

    if (len < 1)
    {
        printf("Error: the length less than 1.\n");
        return false;
    }

    if (errorCode != U_ZERO_ERROR && errorCode != U_BUFFER_OVERFLOW_ERROR)
    {
        printf("Error: (ICU) %s\n", u_errorName(errorCode));
        return false;
    }

    errorCode = U_ZERO_ERROR;

    s = (char*)malloc(len + 1);

    if (!s)
    {
        printf("Error: unable to allocate memory (4)\n");
        return false;
    }

    u_strToUTF8(s, len + 1, &len, str, -1, &errorCode);

    if (errorCode != U_ZERO_ERROR)
    {
        printf("Error: u_strToUTF8(): %s\n", u_errorName(errorCode));
        free(s);
        return false;
    }

    printf("UTF8 string: %s\n", s);

    free(s);

    return true;
}

/*
--------------------
 main();
--------------------
*/

int main()
{

    char testStr[] = "Šešios žąsys su šešiais žąsyčiais.";
    const char locale[] = "lt_LT";

    UChar* uStr;
    UChar* lowerStr;
    UChar* upperStr;

    int32_t length;
    int32_t retLength;
    UErrorCode errorCode = U_ZERO_ERROR;

    printf("%s\n", testStr);
    // printf("strlen: %ld\n", strlen(testStr));
    printf("strlen: %zu\n", strlen(testStr));

    u_strFromUTF8(NULL, 0, &length, testStr, -1, &errorCode);

    if (errorCode != U_ZERO_ERROR && errorCode != U_BUFFER_OVERFLOW_ERROR)
    {
        printf("Error: (ICU) %s\n", u_errorName(errorCode));
        return 1;
    }

    errorCode = U_ZERO_ERROR;

    printf("length: %d\n", length);

    if (length < 1)
    {
        printf("Error: the length less than 1.\n");
        return 1;
    }

    uStr = (UChar*)malloc((length + 1) * sizeof *uStr);

    if (!uStr)
    {
        printf("Error: unable to allocate memory (1).\n");
        return 1;
    }

    u_strFromUTF8(uStr, (length + 1) * sizeof *uStr, &retLength, testStr, -1, &errorCode);

    if (errorCode != U_ZERO_ERROR)
    {
        printf("Error: (ICU) %s\n", u_errorName(errorCode));
        free(uStr);
        return 1;
    }

    printf("retLength: %d\n", retLength);

    if (!printU(uStr))
    {
        printf("Error: printU.\n");
        free(uStr);
        return 1;
    }



    // to lower

    length = u_strToLower(NULL, 0, uStr, -1, locale, &errorCode);

    if (errorCode != U_ZERO_ERROR && errorCode != U_BUFFER_OVERFLOW_ERROR)
    {
        printf("Error: (ICU) %s\n", u_errorName(errorCode));
        free(uStr);
        return 1;
    }

    errorCode = U_ZERO_ERROR;

    printf("length: %d\n", length);

    if (length < 1)
    {
        printf("Error: length less than 1.\n");
        free(uStr);
        return 1;
    }

    lowerStr = (UChar*)malloc((length + 1) * sizeof *lowerStr);

    if (!lowerStr)
    {
        printf("Error: unable to allocate memory (2).\n");
        free(uStr);
        return 1;
    }

    length = u_strToLower(lowerStr, (length + 1) * sizeof *lowerStr, uStr, -1, locale, &errorCode);

    if (errorCode != U_ZERO_ERROR)
    {
        printf("Error: (ICU) %s\n", u_errorName(errorCode));
        free(lowerStr);
        free(uStr);
        return 1;
    }

    if (!printU(lowerStr))
    {
        printf("Error: printU.\n");
        free(lowerStr);
        free(uStr);
        return 1;
    }

    free(lowerStr);



    // to upper

    length = u_strToUpper(NULL, 0, uStr, -1, locale, &errorCode);

    if (errorCode != U_ZERO_ERROR && errorCode != U_BUFFER_OVERFLOW_ERROR)
    {
        printf("Error: (ICU) %s\n", u_errorName(errorCode));
        free(uStr);
        return 1;
    }

    errorCode = U_ZERO_ERROR;

    printf("length: %d\n", length);

    if (length < 1)
    {
        printf("Error: length less than 1.\n");
        free(uStr);
        return 1;
    }

    upperStr = (UChar*)malloc((length + 1) * sizeof *upperStr);

    if (!upperStr)
    {
        printf("Error: unable to allocate memory (3).\n");
        free(uStr);
        return 1;
    }

    length = u_strToUpper(upperStr, (length + 1) * sizeof *upperStr, uStr, -1, locale, &errorCode);

    if (errorCode != U_ZERO_ERROR)
    {
        printf("Error: (ICU) %s\n", u_errorName(errorCode));
        free(upperStr);
        free(uStr);
        return 1;
    }

    if (!printU(upperStr))
    {
        printf("Error: printU.\n");
        free(upperStr);
        free(uStr);
        return 1;
    }

    free(upperStr);



    free(uStr);

    return 0;
}

실행해 보면 이런 출력이 나옵니다.

Šešios žąsys su šešiais žąsyčiais.
strlen: 43
length: 34
retLength: 34
UTF8 string: Šešios žąsys su šešiais žąsyčiais.
length: 34
UTF8 string: šešios žąsys su šešiais žąsyčiais.
length: 34
UTF8 string: ŠEŠIOS ŽĄSYS SU ŠEŠIAIS ŽĄSYČIAIS.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 11/3/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 16  17  [18]  19  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13490정성태12/19/202310105개발 환경 구성: 698. Golang - GLIBC 의존을 없애는 정적 빌드 방법
13489정성태12/19/202310056개발 환경 구성: 697. GoLand에서 ldflags 지정 방법
13488정성태12/18/20239525오류 유형: 884. HTTP 500.0 - 명령행에서 실행한 ASP.NET Core 응용 프로그램을 실행하는 방법
13487정성태12/16/202310633개발 환경 구성: 696. C# - 리눅스용 AOT 빌드를 docker에서 수행 [1]
13486정성태12/15/20239741개발 환경 구성: 695. Nuget config 파일에 값 설정/삭제 방법
13485정성태12/15/20239426오류 유형: 883. dotnet build/restore - error : Root element is missing
13484정성태12/14/202310164개발 환경 구성: 694. Windows 디렉터리 경로를 WSL의 /mnt 포맷으로 구하는 방법
13483정성태12/14/202310418닷넷: 2184. C# - 하나의 resource 파일을 여러 프로그램에서 (AOT 시에도) 사용하는 방법파일 다운로드1
13482정성태12/13/202311643닷넷: 2183. C# - eFriend Expert OCX 예제를 .NET Core/5+ Console App에서 사용하는 방법 [2]파일 다운로드1
13481정성태12/13/202310540개발 환경 구성: 693. msbuild - .NET Core/5+ 프로젝트에서 resgen을 이용한 리소스 파일 생성 방법파일 다운로드1
13480정성태12/12/202312387개발 환경 구성: 692. Windows WSL 2 + Chrome 웹 브라우저 설치
13479정성태12/11/202310029개발 환경 구성: 691. WSL 2 (Ubuntu) + nginx 환경 설정
13477정성태12/8/202310672닷넷: 2182. C# - .NET 7부터 추가된 Int128, UInt128 [1]파일 다운로드1
13476정성태12/8/202310519닷넷: 2181. C# - .NET 8 JsonStringEnumConverter의 AOT를 위한 개선파일 다운로드1
13475정성태12/7/202310775닷넷: 2180. .NET 8 - 함수 포인터에 대한 Reflection 정보 조회파일 다운로드1
13474정성태12/6/202310355개발 환경 구성: 690. 닷넷 코어/5+ 버전의 ilasm/ildasm 실행 파일 구하는 방법 - 두 번째 이야기
13473정성태12/5/202310698닷넷: 2179. C# - 값 형식(Blittable)을 메모리 복사를 이용해 바이트 배열로 직렬화/역직렬화파일 다운로드1
13472정성태12/4/202310113C/C++: 164. Visual C++ - InterlockedCompareExchange128 사용 방법
13471정성태12/4/202310648Copilot - To enable GitHub Copilot, authorize this extension using GitHub's device flow
13470정성태12/2/202311264닷넷: 2178. C# - .NET 8부터 COM Interop에 대한 자동 소스 코드 생성 도입 [1]파일 다운로드1
13469정성태12/1/202311170닷넷: 2177. C# - (Interop DLL 없이) CoClass를 이용한 COM 개체 생성 방법파일 다운로드1
13468정성태12/1/202310176닷넷: 2176. C# - .NET Core/5+부터 달라진 RCW(Runtime Callable Wrapper) 대응 방식파일 다운로드1
13467정성태11/30/202310933오류 유형: 882. C# - Unhandled exception. System.Runtime.InteropServices.COMException (0x800080A5)파일 다운로드1
13466정성태11/29/202310759닷넷: 2175. C# - DllImport 메서드의 AOT 지원을 위한 LibraryImport 옵션
13465정성태11/28/202310466개발 환경 구성: 689. MSBuild - CopyToOutputDirectory가 "dotnet publish" 시에는 적용되지 않는 문제파일 다운로드1
13464정성태11/28/202310371닷넷: 2174. C# - .NET 7부터 UnmanagedCallersOnly 함수 export 기능을 AOT 빌드에 통합파일 다운로드1
... 16  17  [18]  19  20  21  22  23  24  25  26  27  28  29  30  ...