Microsoft MVP성태의 닷넷 이야기
닷넷: 2153. C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법 [링크 복사], [링크+제목 복사],
조회: 2730
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




... [31]  32  33  34  35  36  37  38  39  40  41  42  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
12856정성태11/23/20218907.NET Framework: 1121. C# - 동일한 IP:Port로 바인딩 가능한 서버 소켓 [2]
12855정성태11/13/20216248개발 환경 구성: 605. Azure App Service - Kudu SSH 환경에서 FTP를 이용한 파일 전송
12854정성태11/13/20217814개발 환경 구성: 604. Azure - 윈도우 VM에서 FTP 여는 방법
12853정성태11/10/20216168오류 유형: 766. Azure App Service - JBoss 호스팅 생성 시 "This region has quota of 0 PremiumV3 instances for your subscription. Try selecting different region or SKU."
12851정성태11/1/20217562스크립트: 34. 파이썬 - MySQLdb 기본 예제 코드
12850정성태10/27/20218736오류 유형: 765. 우분투에서 pip install mysqlclient 실행 시 "OSError: mysql_config not found" 오류
12849정성태10/17/20217870스크립트: 33. JavaScript와 C#의 시간 변환 [1]
12848정성태10/17/20218825스크립트: 32. 파이썬 - sqlite3 기본 예제 코드 [1]
12847정성태10/14/20218665스크립트: 31. 파이썬 gunicorn - WORKER TIMEOUT 오류 발생
12846정성태10/7/20218436스크립트: 30. 파이썬 __debug__ 플래그 변수에 따른 코드 실행 제어
12845정성태10/6/20218262.NET Framework: 1120. C# - BufferBlock<T> 사용 예제 [5]파일 다운로드1
12844정성태10/3/20216256오류 유형: 764. MSI 설치 시 "... is accessible and not read-only." 오류 메시지
12843정성태10/3/20216714스크립트: 29. 파이썬 - fork 시 기존 클라이언트 소켓 및 스레드의 동작파일 다운로드1
12842정성태10/1/202125060오류 유형: 763. 파이썬 오류 - AttributeError: type object '...' has no attribute '...'
12841정성태10/1/20218526스크립트: 28. 모든 파이썬 프로세스에 올라오는 특별한 파일 - sitecustomize.py
12840정성태9/30/20218626.NET Framework: 1119. Entity Framework의 Join 사용 시 다중 칼럼에 대한 OR 조건 쿼리파일 다운로드1
12839정성태9/15/20219674.NET Framework: 1118. C# 11 - 제네릭 타입의 특성 적용파일 다운로드1
12838정성태9/13/20219327.NET Framework: 1117. C# - Task에 전달한 Action, Func 유형에 따라 달라지는 async/await 비동기 처리 [2]파일 다운로드1
12837정성태9/11/20218231VC++: 151. Golang - fmt.Errorf, errors.Is, errors.As 설명
12836정성태9/10/20217848Linux: 45. 리눅스 - 실행 중인 다른 프로그램의 출력을 확인하는 방법
12835정성태9/7/20219078.NET Framework: 1116. C# 10 - (15) CallerArgumentExpression 특성 추가 [2]파일 다운로드1
12834정성태9/7/20217479오류 유형: 762. Visual Studio 2019 Build Tools - 'C:\Program' is not recognized as an internal or external command, operable program or batch file.
12833정성태9/6/20216929VC++: 150. Golang - TCP client/server echo 예제 코드파일 다운로드1
12832정성태9/6/20217786VC++: 149. Golang - 인터페이스 포인터가 의미 있을까요?
12831정성태9/6/20216327VC++: 148. Golang - 채널에 따른 다중 작업 처리파일 다운로드1
12830정성태9/6/20218591오류 유형: 761. Internet Explorer에서 파일 다운로드 시 "Your current security settings do not allow this file to be downloaded." 오류
... [31]  32  33  34  35  36  37  38  39  40  41  42  43  44  45  ...