Microsoft MVP성태의 닷넷 이야기
닷넷: 2153. C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법 [링크 복사], [링크+제목 복사]
조회: 2699
글쓴 사람
정성태 (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)
13306정성태4/3/20233679Windows: 243. Win32 - 윈도우(cbWndExtra) 및 윈도우 클래스(cbClsExtra) 저장소 사용 방법
13305정성태4/1/20234050Windows: 242. Win32 - 시간 만료를 갖는 MessageBox 대화창 구현 (쉬운 버전)파일 다운로드1
13304정성태3/31/20234398VS.NET IDE: 181. Visual Studio - C/C++ 프로젝트에 application manifest 적용하는 방법
13303정성태3/30/20233754Windows: 241. 환경 변수 %PATH%에 DLL을 찾는 규칙
13302정성태3/30/20234376Windows: 240. RDP 환경에서 바뀌는 %TEMP% 디렉터리 경로
13301정성태3/29/20234465Windows: 239. C/C++ - Windows 10 Version 1607부터 지원하는 /DEPENDENTLOADFLAG 옵션파일 다운로드1
13300정성태3/28/20234111Windows: 238. Win32 - Modal UI 창에 올바른 Owner(HWND)를 설정해야 하는 이유
13299정성태3/27/20233885Windows: 237. Win32 - 모든 메시지 루프를 탈출하는 WM_QUIT 메시지
13298정성태3/27/20233867Windows: 236. Win32 - MessageBeep 소리가 안 들린다면?
13297정성태3/26/20234529Windows: 235. Win32 - Code Modal과 UI Modal
13296정성태3/25/20233860Windows: 234. IsDialogMessage와 협업하는 WM_GETDLGCODE Win32 메시지 [1]파일 다운로드1
13295정성태3/24/20234145Windows: 233. Win32 - modeless 대화창을 modal처럼 동작하게 만드는 방법파일 다운로드1
13294정성태3/22/20234299.NET Framework: 2105. LargeAddressAware 옵션이 적용된 닷넷 32비트 프로세스의 가용 메모리 - 두 번째
13293정성태3/22/20234353오류 유형: 853. dumpbin - warning LNK4048: Invalid format file; ignored
13292정성태3/21/20234474Windows: 232. C/C++ - 일반 창에도 사용 가능한 IsDialogMessage파일 다운로드1
13291정성태3/20/20234848.NET Framework: 2104. C# Windows Forms - WndProc 재정의와 IMessageFilter 사용 시의 차이점
13290정성태3/19/20234342.NET Framework: 2103. C# - 윈도우에서 기본 제공하는 FindText 대화창 사용법파일 다운로드1
13289정성태3/18/20233528Windows: 231. Win32 - 대화창 템플릿의 2진 리소스를 읽어들여 자식 윈도우를 생성하는 방법파일 다운로드1
13288정성태3/17/20233641Windows: 230. Win32 - 대화창의 DLU 단위를 pixel로 변경하는 방법파일 다운로드1
13287정성태3/16/20233806Windows: 229. Win32 - 대화창 템플릿의 2진 리소스를 읽어들여 윈도우를 직접 띄우는 방법파일 다운로드1
13286정성태3/15/20234247Windows: 228. Win32 - 리소스에 포함된 대화창 Template의 2진 코드 해석 방법
13285정성태3/14/20233833Windows: 227. Win32 C/C++ - Dialog Procedure를 재정의하는 방법파일 다운로드1
13284정성태3/13/20234057Windows: 226. Win32 C/C++ - Dialog에서 값을 반환하는 방법파일 다운로드1
13283정성태3/12/20233597오류 유형: 852. 파이썬 - TypeError: coercing to Unicode: need string or buffer, NoneType found
13282정성태3/12/20233929Linux: 58. WSL - nohup 옵션이 필요한 경우
13281정성태3/12/20233854Windows: 225. 윈도우 바탕화면의 아이콘들이 넓게 퍼지는 경우 [2]
1  2  3  4  5  6  7  8  9  10  11  12  [13]  14  15  ...