Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 4개 있습니다.)
(시리즈 글이 7개 있습니다.)
.NET Framework: 969. .NET Framework 및 .NET 5 - UnmanagedCallersOnly 특성 사용
; https://www.sysnet.pe.kr/2/0/12412

.NET Framework: 970. .NET 5 / .NET Core - UnmanagedCallersOnly 특성을 사용한 함수 내보내기
; https://www.sysnet.pe.kr/2/0/12413

.NET Framework: 971. UnmanagedCallersOnly 특성과 DNNE 사용
; https://www.sysnet.pe.kr/2/0/12415

.NET Framework: 972. DNNE가 출력한 NE DLL을 직접 생성하는 방법
; https://www.sysnet.pe.kr/2/0/12421

.NET Framework: 973. .NET 5, .NET Framework에서만 허용하는 UnmanagedCallersOnly 사용예
; https://www.sysnet.pe.kr/2/0/12422

.NET Framework: 976. UnmanagedCallersOnly + C# 9.0 함수 포인터 사용 시 x86 빌드에서 오동작하는 문제
; https://www.sysnet.pe.kr/2/0/12431

닷넷: 2174. C# - .NET 7부터 UnmanagedCallersOnly 함수 export 기능을 AOT 빌드에 통합
; https://www.sysnet.pe.kr/2/0/13464




C# - .NET 7부터 UnmanagedCallersOnly 함수 export 기능을 AOT 빌드에 통합

예전에,

.NET 5 / .NET Core - UnmanagedCallersOnly 특성을 사용한 함수 내보내기
; https://www.sysnet.pe.kr/2/0/12413

UnmanagedCallersOnly 특성을 이용해 .NET DLL에서 Win32 API와 같은 식의 export 기능을 소개한 적이 있습니다. 그런데, 이 과정이 .NET 7의 "PublishAot" 옵션과 만나면서 더 쉽게 바뀌었습니다.

그래서 예전 글의 예제를, 단순히 다음과 같이 구현해 주고,

using System.Runtime.InteropServices;

namespace ClassLibrary2;

public class Class1
{
    [UnmanagedCallersOnly(EntryPoint = "mymethod")]
    public static void MyMethod(nint ptrText)
    {
        if (ptrText == IntPtr.Zero)
        {
            return;
        }

        string? text = Marshal.PtrToStringUni(ptrText);
        Console.WriteLine($"{DateTime.Now} {text}");
    }
}

csproj에 PublishAot, RuntimeIdentifier 옵션만 추가한 다음,

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <TargetFramework>net7.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
        <RuntimeIdentifier>win-x64</RuntimeIdentifier>
        <PublishAot>true</PublishAot>
    </PropertyGroup>

</Project>

명령행에서 "dotnet publish" 명령만 수행하면 됩니다.

C:\temp\ClassLibrary2> dotnet publish
MSBuild version 17.8.3+195e7f5a3 for .NET
  Determining projects to restore...
  All projects are up-to-date for restore.
  ClassLibrary2 -> C:\temp\ClassLibrary2\bin\Debug\net7.0\win-x64\ClassLibrary2.dll
  Generating native code
     Creating library bin\Debug\net7.0\win-x64\native\ClassLibrary2.lib and object bin\Debug\net7.0\win-x64\native\ClassLibrary2.exp
  ClassLibrary2 -> C:\temp\ClassLibrary2\bin\Debug\net7.0\win-x64\publish\

그럼, 소스 코드 내에서의 UnmanagedCallersOnly + EntryPoint 값이 부여된 것에 대해 자동으로 Win32 EXPORT 함수로 등록해 줍니다.

이후 사용하는 측에서는, 저렇게 생성한 (AOT로 빌드된) ClassLibrary2.dll 파일을 EXE 측에 복사해 둔 다음 DllImport를 연결한 코드를 수행하면 됩니다.

using System.Runtime.InteropServices;

namespace ConsoleApp1;

internal class Program
{
    // 받는 측에서 text 인자를 Unicode로 취급하므로 반드시 MarshalAs로 LPWStr 값을 지정 (기본값은 ANSI)
    [DllImport(@"ClassLibrary2.dll")]
    private static extern int mymethod([MarshalAs(UnmanagedType.LPWStr)] string text);

    static void Main(string[] args)
    {
        mymethod("TEST");
    }
}




개발을 좀 편리하게 하려면, (AOT로 publish된) ClassLibrary2.dll 출력 파일을 EXE 프로젝트 측에 연결하는 것이 좋습니다.

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net8.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
        
    </PropertyGroup>

    <ItemGroup>
        <None Include="..\ClassLibrary2\bin\$(Configuration)\net7.0\win-x64\publish\*">
            <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
        </None>
    </ItemGroup>

</Project>

비록 여전히 ClassLibrary2 프로젝트의 소스 코드가 변경되면 명령행에서 "dotnet publish"를 수행해야 하지만 그래도 일단 배포가 되면 CopyToOutputDirectory까지 연결이 되므로 그 외의 수작업은 줄어듭니다.

게다가 PDB 파일까지 함께 배포되므로, ClassLibrary2의 코드를 디버깅할 수도 있는데요, 단지 AOT로 빌드된 네이티브 코드로 다뤄지기 때문에 "Launch Profiles" 설정에서 "Enable native code debugging" 옵션은 켜야 합니다.

unmanaged_export_debug_1.png

Enable debugging for managed and native code together, also known as mixed-mode debugging.




하는 김에, 할당한 메모리를 반환값으로 사용하는 경우 호출 측에서의 메모리 해제를 다뤄볼까요? ^^ 이를 위해 다음과 같은 export 함수를 만들고,

[UnmanagedCallersOnly(EntryPoint = "Concat")]
public static char* Concat(char* text1, char* text2)
{
    int len1 = GetTextLen(text1);
    int len2 = GetTextLen(text2);

    int dstSize = (len1 + len2 + 1) * 2;
    nint pBuffer = Marshal.AllocHGlobal(dstSize);

    System.Buffer.MemoryCopy(text1, (void*)pBuffer, dstSize, len1 * 2);
    System.Buffer.MemoryCopy(text2, (void*)(pBuffer + (len1 * 2)), dstSize - (len1 * 2), len2 * 2);
    *((char*)(pBuffer + dstSize - 2)) = '\0';

    return (char*)pBuffer;
}

private static int GetTextLen(char* ptr)
{
    int len = 0;

    while (*ptr != 0)
    {
        len++;
        ptr++;
    }

    return len;
}

사용은 이렇게 할 텐데요,

using System.Runtime.InteropServices;

namespace ConsoleApp1;

internal partial class Program
{
    [DllImport(@"ClassLibrary2.dll")]
    [return: MarshalAs(UnmanagedType.LPWStr)]
    public static extern string Concat([MarshalAs(UnmanagedType.LPWStr)] string text1, [MarshalAs(UnmanagedType.LPWStr)] string text2);

    static void Main(string[] args)
    {
        while (true)
        {
            Console.WriteLine($"Concat-Output: {Concat("test is ", "good")}");
        }
    }
}

그렇다면, 저 코드는 Marshal.AllocHGlobal을 무한 루프로 실행하기 때문에 메모리 누수가 발생할까요? 의외로, 발생하지 않습니다. 왜냐하면, string으로 마샬링을 처리하는 런타임 생성 코드에서 자동으로 Marshal.FreeHGlobal을 호출해 주기 때문입니다.

물론, string이 아닌, 포인터로 직접 받도록 signature를 지정하면,

[DllImport(@"ClassLibrary2.dll")]
public static extern nint Concat([MarshalAs(UnmanagedType.LPWStr)] string text1,
    [MarshalAs(UnmanagedType.LPWStr)] string text2);

static void Main(string[] args)
{
    mymethod("TEST");

    while (true)
    {
        nint result = Concat("test is ", "good"); // 메모리 누수
    }
}

이때는 메모리 누수가 발생하게 됩니다. 따라서 저렇게 했다면 반드시 호출 측에서 메모리 정리까지 해야 합니다.

nint result = Concat("test is ", "good");
Marshal.FreeHGlobal(result); // 호출 측에서 명시적인 메모리 해제

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




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 11/29/2023]

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

비밀번호

댓글 작성자
 




... 16  17  18  19  20  21  [22]  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13083정성태6/20/20227326.NET Framework: 2024. .NET 7에 도입된 GC의 메모리 해제에 대한 segment와 region의 차이점 [2]
13082정성태6/19/20226356.NET Framework: 2023. C# - Process의 I/O 사용량을 보여주는 GetProcessIoCounters Win32 API파일 다운로드1
13081정성태6/17/20226412.NET Framework: 2022. C# - .NET 7 Preview 5 신규 기능 - System.IO.Stream ReadExactly / ReadAtLeast파일 다운로드1
13080정성태6/17/20227016개발 환경 구성: 643. Visual Studio 2022 17.2 버전에서 C# 11 또는 .NET 7.0 preview 적용
13079정성태6/17/20224664오류 유형: 814. 파이썬 - Error: The file/path provided (...) does not appear to exist
13078정성태6/16/20226765.NET Framework: 2021. WPF - UI Thread와 Render Thread파일 다운로드1
13077정성태6/15/20227075스크립트: 40. 파이썬 - PostgreSQL 환경 구성
13075정성태6/15/20226039Linux: 50. Linux - apt와 apt-get의 차이 [2]
13074정성태6/13/20226347.NET Framework: 2020. C# - NTFS 파일에 사용자 정의 속성값 추가하는 방법파일 다운로드1
13073정성태6/12/20226575Windows: 207. Windows Server 2022에 도입된 WSL 2
13072정성태6/10/20226856Linux: 49. Linux - ls 명령어로 출력되는 디렉터리 색상 변경 방법
13071정성태6/9/20227439스크립트: 39. Python에서 cx_Oracle 환경 구성
13070정성태6/8/20227240오류 유형: 813. Windows 11에서 입력 포커스가 바뀌는 문제 [1]
13069정성태5/26/20229471.NET Framework: 2019. C# - .NET에서 제공하는 3가지 Timer 비교 [2]
13068정성태5/24/20227996.NET Framework: 2018. C# - 일정 크기를 할당하는 동안 GC를 (가능한) 멈추는 방법 [1]파일 다운로드1
13067정성태5/23/20227303Windows: 206. Outlook - 1년 이상 지난 메일이 기본적으로 안 보이는 문제
13066정성태5/23/20226659Windows: 205. Windows 11 - Windows + S(또는 Q)로 뜨는 작업 표시줄의 검색 바가 동작하지 않는 경우
13065정성태5/20/20227311.NET Framework: 2017. C# - Windows I/O Ring 소개 [2]파일 다운로드1
13064정성태5/18/20226914.NET Framework: 2016. C# - JIT 컴파일러의 인라인 메서드 처리 유무
13063정성태5/18/20227337.NET Framework: 2015. C# - 인라인 메서드(inline methods)
13062정성태5/17/20228058.NET Framework: 2014. C# - async/await 그리고 스레드 (4) 비동기 I/O 재현파일 다운로드1
13061정성태5/16/20226893.NET Framework: 2013. C# - FILE_FLAG_OVERLAPPED가 적용된 파일의 읽기/쓰기 시 Position 관리파일 다운로드1
13060정성태5/15/20229386.NET Framework: 2012. C# - async/await 그리고 스레드 (3) Task.Delay 재현파일 다운로드1
13059정성태5/14/20227805.NET Framework: 2011. C# - CLR ThreadPool의 I/O 스레드에 작업을 맡기는 방법 [1]파일 다운로드1
13058정성태5/13/20227701.NET Framework: 2010. C# - ThreadPool.SetMaxThreads 사용법
13057정성태5/12/20229390오류 유형: 812. 파이썬 - ImportError: cannot import name ...
... 16  17  18  19  20  21  [22]  23  24  25  26  27  28  29  30  ...