Microsoft MVP성태의 닷넷 이야기
닷넷: 2180. .NET 8 - 함수 포인터에 대한 Reflection 정보 조회 [링크 복사], [링크+제목 복사],
조회: 2348
글쓴 사람
정성태 (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)
13536정성태1/23/20242595닷넷: 2209. .NET 8 - NonGC Heap / FOH (Frozen Object Heap) [1]
13535정성태1/22/20242454닷넷: 2208. C# - GCHandle 구조체의 메모리 분석
13534정성태1/21/20242255닷넷: 2207. C# - SQL Server DB를 bacpac으로 Export/Import파일 다운로드1
13533정성태1/18/20242470닷넷: 2206. C# - TCP KeepAlive의 서버 측 구현파일 다운로드1
13532정성태1/17/20242360닷넷: 2205. C# - SuperSimpleTcp 사용 시 주의할 점파일 다운로드1
13531정성태1/16/20242253닷넷: 2204. C# - TCP KeepAlive에 새로 추가된 Retry 옵션파일 다운로드1
13530정성태1/15/20242204닷넷: 2203. C# - Python과의 AES 암호화 연동파일 다운로드1
13529정성태1/15/20242066닷넷: 2202. C# - PublishAot의 glibc에 대한 정적 링킹하는 방법
13528정성태1/14/20242189Linux: 68. busybox 컨테이너에서 실행 가능한 C++, Go 프로그램 빌드
13527정성태1/14/20242133오류 유형: 892. Visual Studio - Failed to launch debug adapter. Additional information may be available in the output window.
13526정성태1/14/20242221닷넷: 2201. C# - Facebook 연동 / 사용자 탈퇴 처리 방법
13525정성태1/13/20242171오류 유형: 891. Visual Studio - Web Application을 실행하지 못하는 IISExpress
13524정성태1/12/20242235오류 유형: 890. 한국투자증권 KIS Developers OpenAPI - GW라우팅 중 오류가 발생했습니다.
13523정성태1/12/20242040오류 유형: 889. Visual Studio - error : A project with that name is already opened in the solution.
13522정성태1/11/20242209닷넷: 2200. C# - HttpClient.PostAsJsonAsync 호출 시 "Transfer-Encoding: chunked" 대신 "Content-Length" 헤더 처리
13521정성태1/11/20242272닷넷: 2199. C# - 한국투자증권 KIS Developers OpenAPI의 WebSocket Ping, Pong 처리
13520정성태1/10/20242017오류 유형: 888. C# - Unable to resolve service for type 'Microsoft.Extensions.ObjectPool.ObjectPool`....'
13519정성태1/10/20242107닷넷: 2198. C# - Reflection을 이용한 ClientWebSocket의 Ping 호출파일 다운로드1
13518정성태1/9/20242370닷넷: 2197. C# - ClientWebSocket의 Ping, Pong 처리
13517정성태1/8/20242210스크립트: 63. Python - 공개 패키지를 이용한 위성 이미지 생성 (pystac_client, odc.stac)
13516정성태1/7/20242320닷넷: 2196. IIS - AppPool의 "Disable Overlapped Recycle" 옵션의 부작용
13515정성태1/6/20242598닷넷: 2195. async 메서드 내에서 C# 7의 discard 구문 활용 사례 [1]
13514정성태1/5/20242276개발 환경 구성: 702. IIS - AppPool의 "Disable Overlapped Recycle" 옵션
13513정성태1/5/20242202닷넷: 2194. C# - WebActivatorEx / System.Web의 PreApplicationStartMethod 특성
13512정성태1/4/20242160개발 환경 구성: 701. IIS - w3wp.exe 프로세스의 ASP.NET 런타임을 항상 Warmup 모드로 유지하는 preload Enabled 설정
13511정성태1/4/20242179닷넷: 2193. C# - ASP.NET Web Application + OpenAPI(Swashbuckle) 스펙 제공
1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...