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

비밀번호

댓글 작성자
 




[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13608정성태4/26/2024417닷넷: 2249. C# - 부모의 필드/프로퍼티에 대해 서로 다른 자식 클래스 간에 Reflection 접근이 동작할까요?파일 다운로드1
13607정성태4/25/2024415닷넷: 2248. C# - 인터페이스 타입의 다중 포인터를 인자로 갖는 C/C++ 함수 연동
13606정성태4/24/2024429닷넷: 2247. C# - tensorflow 연동 (MNIST 예제)파일 다운로드1
13605정성태4/23/2024664닷넷: 2246. C# - Python.NET을 이용한 파이썬 소스코드 연동파일 다운로드1
13604정성태4/22/2024688오류 유형: 901. Visual Studio - Unable to set the next statement. Set next statement cannot be used in '[Exception]' call stack frames.
13603정성태4/21/2024873닷넷: 2245. C# - IronPython을 이용한 파이썬 소스코드 연동파일 다운로드1
13602정성태4/20/2024937닷넷: 2244. C# - PCM 오디오 데이터를 연속(Streaming) 재생 (Windows Multimedia)파일 다운로드1
13601정성태4/19/2024965닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/2024975닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024936닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024978닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드2
13597정성태4/15/2024973닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/20241079닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/20241069닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241082닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241090닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241226C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241201닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241083Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241158닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241274닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신 [2]파일 다운로드1
13587정성태3/27/20241360오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241533Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241497Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241457개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...