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

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

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/31/2024]

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

비밀번호

댓글 작성자
 




... 106  107  108  109  110  111  112  113  114  [115]  116  117  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11049정성태9/24/201621013오류 유형: 357. 윈도우 백업 시 오류 - 0x81000037
11048정성태9/24/201622042VC++: 100. 전역 변수 유형별 실행 파일 크기 차이점
11047정성태9/21/201625836기타: 61. algospot.com - 양자화(Quantization) 문제 [2]파일 다운로드1
11046정성태9/15/201627497개발 환경 구성: 298. Windows 10 - bash 실행 시 시작 디렉터리 자동 변경
11045정성태9/15/201620145Windows: 119. Windows 10 - bash 명령어 창을 실행했는데 바로 닫히는 경우
11044정성태9/15/201620407VS.NET IDE: 112. Visual Studio 확장 - 편집 화면 내에서 링크를 누르면 외부 웹 브라우저에서 열기
11043정성태9/15/201621821.NET Framework: 606. .NET 스레드 콜 스택 덤프 (7) - ClrMD(Microsoft.Diagnostics.Runtime)를 이용한 방법 [1]파일 다운로드1
11042정성태9/14/201619985오류 유형: 356. Unknown custom metadata item kind: 6
11041정성태9/10/201619460.NET Framework: 605. CLR4 보안 - yield 구문 내에서 SecurityCritical 메서드 사용 불가 - 2번째 이야기
11040정성태9/10/201626757.NET Framework: 604. C# Windows Forms - Drag & Drop 예제 코드 [2]파일 다운로드1
11039정성태9/9/201623238오류 유형: 355. Visual Studio 빌드 오류 - error CS0122: '__ComObject' is inaccessible due to its protection level
11038정성태9/9/201625092VC++: 99. 서로 다른 프로세스에서 WM_DROPFILES 메시지를 전송하는 방법파일 다운로드1
11037정성태9/8/201628322.NET Framework: 603. socket - shutdown 호출이 필요한 사례파일 다운로드1
11036정성태8/29/201624794개발 환경 구성: 297. 소스 코드가 없는 닷넷 어셈블리를 디버깅할 때 지역 변숫값을 확인하는 방법
11035정성태8/29/201620437오류 유형: 354. .NET Reflector - PDB 생성 화면에서 "Clear Store"를 하면 "Index and length must refer to a location within the string" 예외 발생
11034정성태8/25/201624461개발 환경 구성: 296. .NET Core 프로젝트를 NuGet Gallery에 배포하는 방법 [2]
11033정성태8/24/201622352오류 유형: 353. coreclr 빌드 시 error C3249: illegal statement or sub-expression for 'constexpr' function
11032정성태8/23/201621571개발 환경 구성: 295. 최신의 Visual C++ 컴파일러 도구를 사용하는 방법 [1]
11031정성태8/23/201617809오류 유형: 352. Error encountered while pushing to the remote repository: Response status code does not indicate success: 403 (Forbidden).
11030정성태8/23/201620346VS.NET IDE: 111. Team Explorer - 추가한 Git Remote 저장소가 Branch에 보이지 않는 경우
11029정성태8/18/201627486.NET Framework: 602. Process.Start의 cmd.exe에서 stdin만 redirect 하는 방법 [1]파일 다운로드1
11028정성태8/15/201621530오류 유형: 351. Octave 설치 시 JRE 경로 문제
11027정성태8/15/201622609.NET Framework: 601. ElementHost 컨트롤의 메모리 누수 현상
11026정성태8/13/201623583Math: 19. 행렬 연산으로 본 해밍코드
11025정성태8/12/201622305개발 환경 구성: 294. .NET Core 프로젝트에서 "Copy to Output Directory" 처리 [1]
11024정성태8/12/201621618오류 유형: 350. "nProtect GameMon" 실행 중에는 Visual Studio 디버깅이 안됩니다! [1]
... 106  107  108  109  110  111  112  113  114  [115]  116  117  118  119  120  ...