Microsoft MVP성태의 닷넷 이야기
닷넷: 2153. C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법 [링크 복사], [링크+제목 복사],
조회: 2731
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법

아래와 같은 글이 있군요. ^^

How can I convert between IANA time zones and Windows registry-based time zones?
; https://devblogs.microsoft.com/oldnewthing/20210527-00/?p=105255

위의 글에서는 icu.dll에 있는 함수 ucal_getWindowsTimeZoneID, ucal_getTimeZoneIDForWindowsID 2개를 이용해 변환을 하고 있는데요, C#에서는 .NET 6부터 그에 대응하는 TryConvertIanaIdToWindowsId, TryConvertWindowsIdToIanaId 메서드를 각각 제공합니다. (.NET 5 이하라면 P/Invoke로 대신해야 합니다.)

TimeZoneInfo.TryConvertIanaIdToWindowsId Method
; https://learn.microsoft.com/en-us/dotnet/api/system.timezoneinfo.tryconvertianaidtowindowsid

TimeZoneInfo.TryConvertWindowsIdToIanaId Method
; https://learn.microsoft.com/en-us/dotnet/api/system.timezoneinfo.tryconvertwindowsidtoianaid

// 아래의 코드는, How can I convert between IANA time zones and Windows registry-based time zones? 글에 실린 C++ 예제 코드를 C#으로 변환한 것과 같은 효과를 갖습니다.

if (TimeZoneInfo.TryConvertIanaIdToWindowsId("America/Vancouver", out string windowsTimeZoneId))
{
    Console.WriteLine(windowsTimeZoneId); // 출력 결과: Pacific Standard Time
}

if (TimeZoneInfo.TryConvertWindowsIdToIanaId("Pacific Standard Time", out string ianaTimeZoneId))
{
    Console.WriteLine(ianaTimeZoneId); // 출력 결과: America/Vancouver
}

또한, 기존 NLS 대신 ICU를 사용하므로 아래의 코드 수행 결과도 달라집니다.

System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("de");
string text = string.Format("{0:C}", 100);
Console.WriteLine(text); // 출력 결과: 100,00 ¤

NLS가 사용되는 경우에는 출력 결과가 "100,00 €"였지만 ICU를 사용하면서 화폐 단위가 "¤" (scarab) 국제 통화 기호로 바뀝니다.




현재 (c:\Windows\system32 디렉터리에 위치한) icu.dll은 윈도우 서버 버전의 경우 2019 이상, 클라이언트 버전의 경우 Windows 10 1703 이상에서만 기본 포함하고 있다는 점을 유의해야 합니다.

그런 탓에 TryConvertIanaIdToWindowsId, TryConvertWindowsIdToIanaId 메서드를 (예를 들어) Windows Server 2016 환경에서 호출하면 모두 false를 반환하면서 변환에 실패합니다. icu.dll을 내장하지 않은 윈도우 버전이라면, 그냥 직접 빌드한 DLL을 닷넷 응용 프로그램과 함께 배포하는 것도 가능한데요, vcpkg를 이용하면 간단하게 빌드할 수 있고,

C:\vcpkg> vcpkg search | findstr icu
...[생략]...
icu                      72.1#3           Mature and widely used Unicode and localization library.
...[생략]...

C:\vcpkg> vcpkg install icu[core]:x64-windows
...[생략]...

그럼 다음과 같은 결과물 파일들이 나옵니다.

icudt72.dll
icuin72.dll
icuio72.dll
icutu72.dll
icuuc72.dll

보는 바와 같이 "72"라는 버전 번호가 함께 붙는데요, 심지어 내부의 API들까지 모두 버전 번호가 따라붙어 빌드가 됩니다.

C:\vcpkg\installed\x64-windows\bin> dumpbin /EXPORTS icuin72.dll | findstr ucal_getWindowsTimeZoneID
       5794 16A1 0014CEF0 ucal_getWindowsTimeZoneID_72 = ucal_getWindowsTimeZoneID_72

그래서, 우리가 직접 P/Invoke interop을 하려면 매우 귀찮아질 수 있는데요, 다행히 닷넷 런타임에서 이러한 다양성을 고려해 설정할 수 있는 옵션을 제공하고 있습니다.

.NET globalization and ICU 
 - App-local ICU
; https://learn.microsoft.com/en-us/dotnet/core/extensions/globalization-icu#app-local-icu

<ItemGroup>
  <RuntimeHostConfigurationOption Include="System.Globalization.AppLocalIcu"
    Value="<suffix>:<version> or <version>" />
</ItemGroup>

suffix와 version을 각각 지정할 수 있는데 vcpkg의 경우 기본 빌드에서 suffix를 붙이지는 않으므로 버전만 다음과 같이 지정하면 됩니다.

<ItemGroup>
    <RuntimeHostConfigurationOption Include="System.Globalization.AppLocalIcu" Value="72" />
</ItemGroup>

자, 그럼 통합해 볼까요? ^^ icu 빌드 후 나온 결과물 중에 테스트를 해보면 닷넷을 위해 3개(icuuc72.dll, icudt72.dll, icuin72.dll)가 필요하다는 것을 알 수 있습니다. 따라서 다음과 같은 식으로 csproj를 구성해,

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net6.0</TargetFramework>
    </PropertyGroup>

    <ItemGroup>
      <None Include="..\Libs\x64\icuuc72.dll" Link="icuuc72.dll">
        <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      </None>
      <None Include="..\Libs\x64\icudt72.dll" Link="icudt72.dll">
        <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      </None>
      <None Include="..\Libs\x64\icuin72.dll" Link="icuin72.dll">
        <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      </None>          
    </ItemGroup>

    <ItemGroup>
        <RuntimeHostConfigurationOption Include="System.Globalization.AppLocalIcu" Value="72" />
    </ItemGroup>
</Project>

(위의 경우 ..\Libs\x64 디렉터리에 DLL을 위치해 두고) 빌드 시 EXE 파일이 생성되는 위치에 dll도 함께 복사가 되므로 배포가 용이해집니다.

실제로 해당 파일들을 모두 복사해 Windows Server 2016에서 실행하면 정상적으로 ICU 관련 메서드들이 호출되는 것을 볼 수 있습니다.




문서에 보면, 반대로 ICU가 아닌 윈도우의 기본 NLS 모듈을 사용하도록 만드는 옵션도 있습니다.

Use NLS instead of ICU
; https://learn.microsoft.com/en-us/dotnet/core/extensions/globalization-icu#use-nls-instead-of-icu

따라서, 다음의 옵션을 csproj에 넣은 후,

<ItemGroup>
  <RuntimeHostConfigurationOption Include="System.Globalization.UseNls" Value="true" />
</ItemGroup>

빌드하면 이제는 Windows 11에서도 .NET 5+ 응용 프로그램은 이전과 같은 실행 결과가 나옵니다.

참고로, csproj에 지정한 RuntimeHostConfigurationOption은 결국 빌드 후 결과물로 나오는 "[exe].runtimeconfig.json" 파일에 반영되는 효과만 있는 것입니다.

{
  "runtimeOptions": {
    "tfm": "net6.0",
    "framework": {
      "name": "Microsoft.NETCore.App",
      "version": "6.0.0"
    },
    "configProperties": {
      "System.Globalization.AppLocalIcu": 72,
      "System.Globalization.UseNls": true
    }
  }
}

즉, csproj에 지정하지 않았어도 어떤 식으로든 runtimeconfig.json에 저 설정만 넣어주면 됩니다. 심지어 환경 변수(DOTNET_SYSTEM_GLOBALIZATION_USENLS, DOTNET_SYSTEM_GLOBALIZATION_APPLOCALICU)로도 가능합니다.




그나저나, 우리가 vcpkg로 직접 빌드한 3개의 모듈은 각각의 파일 용량이 icudt72.dll 30MB, icuin72.dll 2.5MB, icuuc72.dll 1.7MB로 꽤나 큽니다. 반면, 윈도우 내장 icu.dll의 경우 2.5MB에 불과한데요, "How can I convert between IANA time zones and Windows registry-based time zones?" 글에 보면, 윈도우도 처음에는 icuuc.dll, icuin.dll로 나뉘어 제공하다가 Windows 10 Version 1903부터 icu.dll 하나로 합쳤다고 합니다.

어쨌든 직접 빌드한 DLL이 적은 용량은 아니므로 배포 파일에 포함해야 한다면 아마도 윈도우 대상에 따라 셋업 파일을 제공하는 것도 고민해야 할 것입니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 10/30/2023]

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

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13358정성태5/17/20233825.NET Framework: 2125. C# - Semantic Kernel의 Semantic Memory 사용 예제 [1]파일 다운로드1
13357정성태5/16/20233609.NET Framework: 2124. C# - Semantic Kernel의 Planner 사용 예제파일 다운로드1
13356정성태5/15/20233934DDK: 10. Device Driver 테스트 설치 관련 오류 (Code 37, Code 31) 및 인증서 관련 정리
13355정성태5/12/20233874.NET Framework: 2123. C# - Semantic Kernel의 ChatGPT 대화 구현 [1]파일 다운로드1
13354정성태5/12/20234129.NET Framework: 2122. C# - "Use Unicode UTF-8 for worldwide language support" 설정을 한 경우, 한글 입력이 '\0' 문자로 처리
13352정성태5/12/20233753.NET Framework: 2121. C# - Semantic Kernel의 대화 문맥 유지파일 다운로드1
13351정성태5/11/20234235VS.NET IDE: 185. Visual Studio - 원격 Docker container 내에 실행 중인 응용 프로그램에 대한 디버깅 [1]
13350정성태5/11/20233514오류 유형: 859. Windows Date and Time - Unable to continue. You do not have permission to perform this task
13349정성태5/11/20233817.NET Framework: 2120. C# - Semantic Kernel의 Skill과 Function 사용 예제파일 다운로드1
13348정성태5/10/20233706.NET Framework: 2119. C# - Semantic Kernel의 "Basic Loading of the Kernel" 예제
13347정성태5/10/20234129.NET Framework: 2118. C# - Semantic Kernel의 Prompt chaining 예제파일 다운로드1
13346정성태5/10/20233942오류 유형: 858. RDP 원격 환경과 로컬 PC 간의 Ctrl+C, Ctrl+V 복사가 안 되는 문제
13345정성태5/9/20235338.NET Framework: 2117. C# - (OpenAI 기반의) Microsoft Semantic Kernel을 이용한 자연어 처리 [1]파일 다운로드1
13344정성태5/9/20236516.NET Framework: 2116. C# - OpenAI API 사용 - 지원 모델 목록 [1]파일 다운로드1
13343정성태5/9/20234398디버깅 기술: 192. Windbg - Hyper-V VM으로 이더넷 원격 디버깅 연결하는 방법
13342정성태5/8/20234317.NET Framework: 2115. System.Text.Json의 역직렬화 시 필드/속성 주의
13341정성태5/8/20234029닷넷: 2114. C# 12 - 모든 형식의 별칭(Using aliases for any type)
13340정성태5/8/20234128오류 유형: 857. Microsoft.Data.SqlClient.SqlException - 0x80131904
13339정성태5/6/20234861닷넷: 2113. C# 12 - 기본 생성자(Primary Constructors)
13338정성태5/6/20234310닷넷: 2112. C# 12 - 기본 람다 매개 변수파일 다운로드1
13337정성태5/5/20234797Linux: 59. dockerfile - docker exec로 container에 접속 시 자동으로 실행되는 코드 적용
13336정성태5/4/20234614.NET Framework: 2111. C# - 바이너리 출력 디렉터리와 연관된 csproj 설정
13335정성태4/30/20234695.NET Framework: 2110. C# - FFmpeg.AutoGen 라이브러리를 이용한 기본 프로젝트 구성 - Windows Forms파일 다운로드1
13334정성태4/29/20234350Windows: 250. Win32 C/C++ - Modal 메시지 루프 내에서 SetWindowsHookEx를 이용한 Thread 메시지 처리 방법
13333정성태4/28/20233773Windows: 249. Win32 C/C++ - 대화창 템플릿을 런타임에 코딩해서 사용파일 다운로드1
13332정성태4/27/20233873Windows: 248. Win32 C/C++ - 대화창을 위한 메시지 루프 사용자 정의파일 다운로드1
1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...