Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)
(시리즈 글이 6개 있습니다.)
개발 환경 구성: 386. .NET Framework Native compiler 프리뷰 버전 사용법
; https://www.sysnet.pe.kr/2/0/11563

.NET Framework: 2069. .NET 7 - AOT(ahead-of-time) 컴파일
; https://www.sysnet.pe.kr/2/0/13162

닷넷: 2175. C# - DllImport 메서드의 AOT 지원을 위한 LibraryImport 옵션
; https://www.sysnet.pe.kr/2/0/13466

닷넷: 2184. C# - 하나의 resource 파일을 여러 프로그램에서 (AOT 시에도) 사용하는 방법
; https://www.sysnet.pe.kr/2/0/13483

개발 환경 구성: 696. C# - 리눅스용 AOT 빌드를 docker에서 수행
; https://www.sysnet.pe.kr/2/0/13487

닷넷: 2202. C# - PublishAot의 glibc에 대한 정적 링킹하는 방법
; https://www.sysnet.pe.kr/2/0/13529




C# - DllImport 메서드의 AOT 지원을 위한 LibraryImport 옵션

P/Invoke는 DllImport 호출 시 .NET 런타임 측에서 동적으로 코드를 생성해 연결하는 식으로 동작합니다. 이에 대해서는 전에 한번 다룬 적이 있습니다.

windbg - C# PInvoke 호출 시 마샬링을 담당하는 함수 분석
; https://www.sysnet.pe.kr/2/0/12065

이러한 동적 코드 생성이 AOT 시에는 문제가 된다고 하는데요,

Source generation for platform invokes
; https://learn.microsoft.com/en-us/dotnet/standard/native-interop/pinvoke-source-generation

The IL stub handles marshalling of parameters and return values and calling the unmanaged code while respecting settings on DllImportAttribute that affect how the unmanaged code should be invoked (for example, SetLastError). Since this IL stub is generated at run time, it isn't available for ahead-of-time (AOT) compiler or IL trimming scenarios


그래서 그 해법으로 .NET 7부터 LibraryImport를 이용한 방법을 소개하고 있습니다. 간단하게, LibraryImport 속성이 어떻게 동작하는지 한번 파헤쳐 볼까요? ^^

LibraryImportAttribute
; https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.libraryimportattribute

예를 들어, 기존에 다음과 같이 DllImport를 사용하던 경우라면,

public class Program
{
    [DllImport(@"ClassLibrary2.dll")]
    public static extern void mymethod([MarshalAs(UnmanagedType.LPWStr)] string text);
}

이것을 LibraryImport로 바꾸기 위해서는 class를 partial로 만들고,

public partial class Program
{
    // ...[생략]...
}

DllImport를 적용했던 메서드를 partial과 함께 LibraryImport 특성으로 대체한 다음, 마샬링이 필요한 참조 형식의 인자에 대해서는 어떻게 처리해야 하는지를 알려주는 옵션을 적용하면 됩니다. (string 형식에 대해서만 지원합니다.)

// "string text" 인자가 참조형이므로 StringMarshalling 옵션을 이용해 Utf16으로 하도록 명시

[LibraryImport(@"ClassLibrary2.dll", StringMarshalling = StringMarshalling.Utf16)]
public static partial void mymethod(string text);

이렇게 바꾸면 C# 컴파일러는 LibraryImport 특성이 있는 partial 메서드에 대해 다음과 같은 식으로 partial class + partial method를 적용해 소스 코드를 생성해 줍니다.

// unsafe가 들어가기 때문에, LibraryImport를 적용한 경우 프로젝트 옵션에 AllowUnsafeBlocks 값을 true로 설정해야 함

// <auto-generated/>
namespace ConsoleApp1
{
    internal unsafe partial class Program
    {
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Interop.LibraryImportGenerator", "8.0.9.3103")]
        [global::System.Runtime.CompilerServices.SkipLocalsInitAttribute]
        private static partial void mymethod(string text)
        {
            // Pin - Pin data in preparation for calling the P/Invoke.
            fixed (void* __text_native = &global::System.Runtime.InteropServices.Marshalling.Utf16StringMarshaller.GetPinnableReference(text))
            {
                __PInvoke((ushort*)__text_native);
            }

            // Local P/Invoke
            [global::System.Runtime.InteropServices.DllImportAttribute("ClassLibrary2.dll", EntryPoint = "mymethod", ExactSpelling = true)]
            static extern unsafe void __PInvoke(ushort* __text_native);
        }
    }
}

그러니까, 참조형 타입에 대해 미리 pinning 등의 작업을 한 후, 원래의 DllImport를 감싼 __PInvoke를 호출하는 식으로 바뀝니다. 결국, DllImport를 다음과 같이 사용하던 것과 별반 다를 게 없습니다.

[DllImport(@"ClassLibrary2.dll")]
public static extern void mymethod(char* text);

fixed (char* ptr = text)
{
    mymethod(ptr);
}




보는 바와 같이 LibraryImport는 간단한 래퍼에 불과한 것으로, DllImport를 사용하는 유형이긴 한데, 전달되는 인자에 대해 부가적인 마샬링 코드를 런타임 측에서 동적으로 생성할 필요가 없도록 강제하는 효과를 갖는 것입니다.

일례로, (마샬링이 필요한) 참조 형식을 전달하려 하면,

[StructLayout(LayoutKind.Sequential)]
public class MyType
{
    public int Age { get; set; }
}

[LibraryImport(@"ClassLibrary2.dll")]
public static partial void InitMyType(MyType instance);

SYSLIB1051 컴파일 오류를 발생시킵니다.

SYSLIB1051: The type 'ConsoleApp1.MyType' is not supported by source-generated P/Invokes. The generated source will not handle marshalling of parameter 'instance'. (https://learn.microsoft.com/dotnet/fundamentals/syslib-diagnostics/syslib1051)


반면 마샬링이 필요 없도록 struct로 바꾸면,

public struct MyType
{
    public int Age { get; set; }
}

/*
// 참고로, 이때 자동 생성하는 partial 메서드는, DllImport로 유형만 바뀐 채로 처리됩니다.
public unsafe partial class Program
{
    [global::System.Runtime.InteropServices.DllImportAttribute("ClassLibrary2.dll", EntryPoint = "InitMyType", ExactSpelling = true)]
    public static extern partial void InitMyType(global::ConsoleApp1.MyType instance);
}
*/

다시 AOT 빌드까지 잘 되지만, 만약 저 struct의 필드에 참조 형식을 포함하게 되면,

public struct MyType
{
    public int Age { get; set; }
    public string Text { get; set; } // 참조 형식
}

재차 SYSLIB1051 오류가 발생합니다. 메서드의 인자에 string이 있는 경우에는 "StringMarshalling = StringMarshalling.Utf16" 옵션을 적용해 LibraryImportGenerator 소스 코드 생성기로 하여금 마샬링 코드를 컴파일 시점에 생성하도록 만들 수 있지만, 저렇게 사용자 타입에 들어가는 유형은 (아직인지는 모르겠지만) LibraryImportGenerator에서 지원하지 않습니다.

검색해 보면, MarshalUsing을 이용해 Custom marshaler까지 제공하면 된다고 하는데요,

Marshalling Function Pointers with .NET 7 LibraryImport
; https://stackoverflow.com/questions/75304403/marshalling-function-pointers-with-net-7-libraryimport

정리하자면, LibraryImport를 사용함으로써 인자의 마샬링 작업만큼은 PInvoke 호출 전에, 즉 컴파일 시점에 끝내겠다는 ^^ 확고한 의지를 보여주는 것과 같다고 하겠습니다. (덤으로 C# 컴파일러로 하여금 유효성 체크를 받을 수도 있고!)

결국 마샬링이 필요 없는 경우라면 DllImport를 기존과 다름없이 사용하셔도 됩니다. 심지어, 문서에서 예를 든 ToLower 메서드도,

[DllImport(
    "nativelib",
    EntryPoint = "to_lower",
    CharSet = CharSet.Unicode)]
internal static extern string ToLower(string str);

// string lower = ToLower("StringToConvert");

PublishAot로 빌드할 때 아무런 문제 없이 잘 실행이 됩니다. 사실, 저 경우는 string에 대해 CharSet 및 pinning 처리를 수반하는 코드가 생성될 텐데도, ... string 정도는 감안하고 특별히 AOT 컴파일러 측에서 처리를 해주는 것인지는 알 수 없지만, 어쨌든 빌드 및 실행까지 됩니다.




돌이켜 보면, P/Inovke 관련해서는 정말 많은 변화가 있었군요. ^^

가령, Microsoft.Windows.CsWin32 패키지를 통한 DllImport를 자동 생성해 주는 것도 있었고,

C# - Win32 API에 대한 P/Invoke를 대신하는 Microsoft.Windows.CsWin32 패키지
; https://www.sysnet.pe.kr/2/0/12540

SuppressGCTransition을 이용한 속도 향상을 꾀하기도 했습니다.

.NET 5+ 환경에서 P/Invoke의 성능을 높이기 위한 SuppressGCTransition 특성
; https://www.sysnet.pe.kr/2/0/13401




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 11/29/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)
13559정성태2/19/20242936오류 유형: 895. ASP.NET - System.Security.SecurityException: 'Requested registry access is not allowed.'
13558정성태2/18/20242157닷넷: 2217. C# - 최댓값이 1인 SemaphoreSlim 보다 Mutex 또는 lock(obj)를 선택하는 것이 나은 이유
13557정성태2/18/20241911Windows: 258. Task Scheduler의 Author 속성 값을 변경하는 방법
13556정성태2/17/20241954Windows: 257. Windows - Symbolic (hard/soft) Link 및 Junction 차이점
13555정성태2/15/20242108닷넷: 2216. C# - SemaphoreSlim 사용 시 주의점
13554정성태2/15/20241854VS.NET IDE: 189. Visual Studio - 닷넷 소스코드 디컴파일 찾기가 안 될 때
13553정성태2/14/20241936닷넷: 2215. windbg - thin/fat lock 없이 동작하는 Monitor.Wait + Pulse
13552정성태2/13/20241885닷넷: 2214. windbg - Monitor.Enter의 thin lock과 fat lock
13551정성태2/12/20242081닷넷: 2213. ASP.NET/Core 웹 응용 프로그램 - 2차 스레드의 예외로 인한 비정상 종료
13550정성태2/11/20242196Windows: 256. C# - Server socket이 닫히면 Accept 시켰던 자식 소켓이 닫힐까요?
13549정성태2/3/20242498개발 환경 구성: 706. C# - 컨테이너에서 실행하기 위한 (소켓) 콘솔 프로젝트 구성
13548정성태2/1/20242327개발 환경 구성: 705. "Docker Desktop for Windows" - ASP.NET Core 응용 프로그램의 소켓 주소 바인딩(IPv4/IPv6 loopback, Any)
13547정성태1/31/20242080개발 환경 구성: 704. Visual Studio - .NET 8 프로젝트부터 dockerfile에 추가된 "USER app" 설정
13546정성태1/30/20241938Windows: 255. (디버거의 영향 등으로) 대상 프로세스가 멈추면 Socket KeepAlive로 연결이 끊길까요?
13545정성태1/30/20241855닷넷: 2212. ASP.NET Core - 우선순위에 따른 HTTP/HTTPS 호스트:포트 바인딩 방법
13544정성태1/30/20241879오류 유형: 894. Microsoft.Data.SqlClient - Could not load file or assembly 'System.Security.Permissions, ...'
13543정성태1/30/20241878Windows: 254. Windows - 기본 사용 중인 5357 포트 비활성화는 방법
13542정성태1/30/20241911오류 유형: 893. Visual Studio - Web Application을 실행하지 못하는 IISExpress - 두 번째 이야기
13541정성태1/29/20241952VS.NET IDE: 188. launchSettings.json의 useSSL 옵션
13540정성태1/29/20242071Linux: 69. 리눅스 - "Docker Desktop for Windows" Container 환경에서 IPv6 Loopback Address 바인딩 오류
13539정성태1/26/20242360개발 환경 구성: 703. Visual Studio - launchSettings.json을 이용한 HTTP/HTTPS 포트 바인딩
13538정성태1/25/20242410닷넷: 2211. C# - NonGC(FOH) 영역에 .NET 개체를 생성파일 다운로드1
13537정성태1/24/20242493닷넷: 2210. C# - Native 메모리에 .NET 개체를 생성파일 다운로드1
13536정성태1/23/20242583닷넷: 2209. .NET 8 - NonGC Heap / FOH (Frozen Object Heap) [1]
13535정성태1/22/20242428닷넷: 2208. C# - GCHandle 구조체의 메모리 분석
13534정성태1/21/20242247닷넷: 2207. C# - SQL Server DB를 bacpac으로 Export/Import파일 다운로드1
1  2  [3]  4  5  6  7  8  9  10  11  12  13  14  15  ...