Microsoft MVP성태의 닷넷 이야기
닷넷: 2180. .NET 8 - 함수 포인터에 대한 Reflection 정보 조회 [링크 복사], [링크+제목 복사]
조회: 2335
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)
(시리즈 글이 5개 있습니다.)
닷넷: 2161. .NET Conf 2023 - Day 1 Blazor 개요 정리
; https://www.sysnet.pe.kr/2/0/13446

닷넷: 2163. .NET 8 - Dynamic PGO를 결합한 성능 향상
; https://www.sysnet.pe.kr/2/0/13448

닷넷: 2178. C# - .NET 8부터 COM Interop에 대한 자동 소스 코드 생성 도입
; https://www.sysnet.pe.kr/2/0/13470

닷넷: 2180. .NET 8 - 함수 포인터에 대한 Reflection 정보 조회
; https://www.sysnet.pe.kr/2/0/13475

닷넷: 2181. C# - .NET 8 JsonStringEnumConverter의 AOT를 위한 개선
; https://www.sysnet.pe.kr/2/0/13476




.NET 8 - 함수 포인터에 대한 Reflection 정보 조회

문서를 보면,

Reflection improvements
; https://learn.microsoft.com/en-us/dotnet/core/whats-new/dotnet-8#reflection-improvements

.NET 5/C# 9.0에 추가되었던 함수 포인터에 대해,

C# 9.0 - (6) 함수 포인터(Function pointers)
; https://www.sysnet.pe.kr/2/0/12374

Reflection 대응이 가능해졌다고 합니다. 예제를 위해,

C++의 inline asm 사용을 .NET으로 포팅하는 방법
; https://www.sysnet.pe.kr/2/0/1267

저 글의 CPUID를 구하는 코드를 (기존의 System.Delegate를 사용하던 방식 대신) 함수 포인터를 이용해 다음과 같이 처리해 보겠습니다.

public class SystemInfo
{
    // ...[생략]...

    delegate* unmanaged[Cdecl]<byte*, void> _cpuIdFunc;

    public SystemInfo()
    {
        byte[] codeBytes = (IntPtr.Size == 4) ? x86CpuIdBytes : x64CpuIdBytes;

        _codePointer = VirtualAlloc(IntPtr.Zero, new UIntPtr((uint)codeBytes.Length), 
            AllocationType.COMMIT | AllocationType.RESERVE, MemoryProtection.EXECUTE_READWRITE 
        );

        Marshal.Copy(codeBytes, 0, _codePointer, codeBytes.Length);

        _cpuIdFunc = (delegate* unmanaged[Cdecl]<byte*, void>)_codePointer;
    }

    // ...[생략]...
}

.NET 7까지는 "delegate* unmanaged[Cdecl]<byte*, void>" 타입은 단순히 포인터에 불과했지만, .NET 8부터는 함수 포인터 타입으로써의 정보를 구할 수 있게 바뀐 것인데요, 그렇다고 해서 _cpuIdFunc 필드에 대고 GetType을 할 수는 없습니다.

Type type = _cpuIdFunc.GetType(); // 컴파일 오류: CS1061

// 또는,

Type type = typeof(_cpuIdFunc); // 컴파일 오류

대신 delegate 정의에 대해 직접 타입을 구하거나,

Type type = typeof(delegate* unmanaged[Cdecl, SuppressGCTransition]<byte*, void>);

클래스의 멤버 필드로 조회해 타입을 구할 수 있습니다.

FieldInfo fieldType = typeof(SystemInfo).GetField(
    nameof(SystemInfo._cpuIdFunc), BindingFlags.NonPublic | BindingFlags.Instance);
Type type = fieldType.FieldType;

특이한 점은, 타입으로써의 Name도 없고 BaseType도 없다는 점입니다.

Console.WriteLine(type.IsClass); // True (타입이긴 해도!)
Console.WriteLine(type.FullName ?? "(null)"); // (null)
Console.WriteLine(type.BaseType ?? "(null)"); // (null)
Console.WriteLine(type); // System.Void(System.Byte*)

단지 해당 타입이 포인터라는 점과,

Console.WriteLine(type.IsFunctionPointer); // True
Console.WriteLine(type.IsUnmanagedFunctionPointer); // True
Console.WriteLine(type.IsPointer); // False (그렇다고 해서 포인터는 아니라는!)

"함수"를 가리키기 때문에 그에 대한 매개변수 정보, 반환값 정보를 구할 수 있도록 했습니다.

Console.WriteLine(type.GetFunctionPointerReturnType()); // System.Void (반환 타입)

foreach (Type parameterType in type.GetFunctionPointerParameterTypes()) // 매개변수 타입
{
    Console.WriteLine($"Parameter type: {parameterType}"); // Parameter type: System.Byte*
}

재미있는 점은, delegate* 타입에 부여한 calling convention 정보를 가져오기 위해 Type이 아닌, FieldInfo의 (.NET 8에 새롭게 추가된) GetModifiedFieldType 메서드를 통해서만 가능하다는 점입니다.

FieldInfo fieldInfo = typeof(SystemInfo).GetField(
    nameof(SystemInfo._cpuIdFunc), BindingFlags.NonPublic | BindingFlags.Instance);
Type type = fieldInfo.FieldType;

Type modifiedType = fieldInfo.GetModifiedFieldType();

Console.WriteLine(type == modifiedType); // False
Console.WriteLine(type == modifiedType.UnderlyingSystemType); // True

foreach (Type callConv in modifiedType.GetFunctionPointerCallingConventions())
{
    Console.WriteLine($"Calling convention: {callConv}"); // Calling convention: System.Runtime.CompilerServices.CallConvCdecl
}

결국, "delegate*"로부터 구한 타입의 경우에는 그 안에 Calling convention에 대한 정보가 있음에도 불구하고 그 정보를 구할 수 없다는 요상한 경우가 나옵니다.

Type type = typeof(delegate* unmanaged[Cdecl]<byte*, void>);
Console.WriteLine($"{type.GetFunctionPointerCallingConventions().Length}"); // 0

마찬가지로, 매개변수에 대한 접근자 정보 역시 GetModifiedFieldType으로 구한 타입으로만 조회할 수 있습니다.

// 제가 만든 예제 코드에서는 modifier가 없으므로 결과가 없습니다.

var modifiers =
    modifiedType.GetFunctionPointerParameterTypes()[0].GetRequiredCustomModifiers();

foreach (Type modreq in modifiers) // [0] 번째 인자의 modifier를 열거
{
    Console.WriteLine($"Required modifier for first parameter: {modreq}");
}




사실 개인적으로는, 함수 포인터의 Reflection 조회 자체에 대해서는 별로 관심은 없었고, 해당 문서를 보면서 보게 된 코드가 더 흥미로웠습니다.

public delegate* unmanaged[Cdecl, SuppressGCTransition]<in int, void> _fp;

처음 C# 9에서 함수 포인터 구문을 접했을 땐,

delegate* managed<int, int, int> p1 = null;

delegate* unmanaged[Stdcall]<int, int, int> p2 = null;

저렇게 "[", "]" 대괄호 안에 올 수 있는 것은 특별히 Calling Convention에 한해서 가능한 거라고 생각했는데요, 실제로는 마치 특성(Attribute)처럼 지정할 수 있다는 것이 흥미로웠습니다.

그런데, 저기에 지정된 Stdcall같은 타입들은 실제로 단순히 class로만 정의돼 있는 것이 맞습니다.

public class CallConvCdecl
{
    public CallConvCdecl() { }
}
public class CallConvFastcall
{
    public CallConvFastcall() { }
}
public class CallConvStdcall
{
    public CallConvStdcall() { }
}

게다가, 함께 지정 가능한 SuppressGCTransition은 특성이 맞습니다.

[AttributeUsage(AttributeTargets.Method, Inherited = false)]
public sealed class SuppressGCTransitionAttribute : Attribute
{
    public SuppressGCTransitionAttribute()
    {
    }
}

오호~~~ 그렇다면 아마도 마이크로소프트 측은 처음부터 저 구문에 특성을 지정할 수 있게 만들지는 않았을 거로 보이는데요, 테스트를 위해 .NET 5 프로젝트를 만들어 다음의 코드를 컴파일해 보면,

using System;

namespace ConsoleApp1
{
    internal unsafe class Program
    {
        delegate* unmanaged[Cdecl, SuppressGCTransition]<byte*, void> _cpuIdFunc; // 컴파일 오류

        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }

    [AttributeUsage(AttributeTargets.Method, Inherited = false)]
    public sealed class SuppressGCTransitionAttribute : Attribute // .NET 6부터 정의됐으므로 일부러 추가
    {
        public SuppressGCTransitionAttribute()
        {
        }
    }
}

이런 오류가 발생합니다.

error CS8890: Type 'CallConvSuppressGCTransition' is not defined.

즉, 이름 규칙을 "CallConv" 접두사를 붙인 것들만 허용한 것입니다. 그렇다고 해서 CallConvSuppressGCTransition 타입을 정의해도 여전히 오류는 발생합니다. 이거저거 테스트해 보면, 결국 .NET 6부터 delegate*에 지정 가능한 특성(?)은 기존에 정의된 Calling Convention 타입들과 특별히 SuppressGCTransition 특성만 지정하도록 제한돼 있는 것을 알 수 있습니다. (일례로, .NET 8.0에서도 AttributeTargets.Method인 사용자 정의 특성을 설정하면 컴파일 오류가 발생합니다.)

뭐랄까, 약간 하드 코딩을 했다는 느낌마저 드는데요, 그렇다고 해도 저런 코드를 작성하게 된 것은 환영할 만합니다.

왜냐하면, delegate* + SuppressGCTransition 조합이야말로 닷넷 세계에서 현존하는 Native API 호출 방식 중 가장 빠른 유형이기 때문입니다.

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




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 12/8/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)
13457정성태11/25/20232277VS.NET IDE: 187. Visual Studio - 16.9 버전부터 추가된 "Display inline type hints" 옵션
13456정성태11/25/20232581닷넷: 2169. C# - OpenAI를 사용해 PDF 데이터를 대상으로 OpenAI 챗봇 작성 [1]파일 다운로드1
13455정성태11/25/20232472닷넷: 2168. C# - Azure.AI.OpenAI 패키지로 OpenAI 사용파일 다운로드1
13454정성태11/23/20232823닷넷: 2167. C# - Qdrant Vector DB를 이용한 Embedding 벡터 값 보관/조회 (Azure OpenAI) [1]파일 다운로드1
13453정성태11/23/20232320오류 유형: 879. docker desktop 설치 시 "Invalid JSON string. (Exception from HRESULT: 0x83750007)"
13452정성태11/22/20232424닷넷: 2166. C# - Azure OpenAI API를 이용해 사용자가 제공하는 정보를 대상으로 검색하는 방법파일 다운로드1
13451정성태11/21/20232555닷넷: 2165. C# - Azure OpenAI API를 이용해 ChatGPT처럼 동작하는 콘솔 응용 프로그램 제작파일 다운로드1
13450정성태11/21/20232364닷넷: 2164. C# - Octokit을 이용한 GitHub Issue 검색파일 다운로드1
13449정성태11/21/20232441개발 환경 구성: 688. Azure OpenAI 서비스 신청 방법
13448정성태11/20/20232678닷넷: 2163. .NET 8 - Dynamic PGO를 결합한 성능 향상파일 다운로드1
13447정성태11/16/20232563닷넷: 2162. ASP.NET Core 웹 사이트의 SSL 설정을 코드로 하는 방법
13446정성태11/16/20232515닷넷: 2161. .NET Conf 2023 - Day 1 Blazor 개요 정리
13445정성태11/15/20232833Linux: 62. 리눅스/WSL에서 CA 인증서를 저장하는 방법
13444정성태11/15/20232590닷넷: 2160. C# 12 - Experimental 특성 지원
13443정성태11/14/20232613개발 환경 구성: 687. OpenSSL로 생성한 사용자 인증서를 ASP.NET Core 웹 사이트에 적용하는 방법
13442정성태11/13/20232433개발 환경 구성: 686. 비주얼 스튜디오로 실행한 ASP.NET Core 사이트를 WSL 2 인스턴스에서 https로 접속하는 방법
13441정성태11/12/20232749닷넷: 2159. C# - ASP.NET Core 프로젝트에서 서버 Socket을 직접 생성하는 방법파일 다운로드1
13440정성태11/11/20232422Windows: 253. 소켓 Listen 시 방화벽의 Public/Private 제어 기능이 비활성화된 경우
13439정성태11/10/20232947닷넷: 2158. C# - 소켓 포트를 미리 시스템에 등록/예약해 사용하는 방법(Port Exclusion Ranges)파일 다운로드1
13438정성태11/9/20232541닷넷: 2157. C# - WinRT 기능을 이용해 윈도우에서 실행 중인 Media App 제어
13437정성태11/8/20232734닷넷: 2156. .NET 7 이상의 콘솔 프로그램을 (dockerfile 없이) 로컬 docker에 배포하는 방법
13436정성태11/7/20232975닷넷: 2155. C# - .NET 8 런타임부터 (Reflection 없이) 특성을 이용해 public이 아닌 멤버 호출 가능
13435정성태11/6/20232904닷넷: 2154. C# - 네이티브 자원을 포함한 관리 개체(예: 스레드)의 GC 정리
13434정성태11/1/20232668스크립트: 62. 파이썬 - class의 정적 함수를 동적으로 교체
13433정성태11/1/20232381스크립트: 61. 파이썬 - 함수 오버로딩 미지원
13432정성태10/31/20232456오류 유형: 878. 탐색기의 WSL 디렉터리 접근 시 "Attempt to access invalid address." 오류 발생
1  2  3  4  5  6  [7]  8  9  10  11  12  13  14  15  ...