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)
13586정성태3/27/20241607Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241503Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241468개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241500Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241625Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
13581정성태3/18/20241778개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
13580정성태3/15/20241312닷넷: 2231. C# - ReceiveTimeout, SendTimeout이 적용되지 않는 Socket await 비동기 호출파일 다운로드1
13579정성태3/13/20241517오류 유형: 899. HTTP Error 500.32 - ANCM Failed to Load dll
13578정성태3/11/20241681닷넷: 2230. C# - 덮어쓰기 가능한 환형 큐 (Circular queue)파일 다운로드1
13577정성태3/9/20241924닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx)
13576정성태3/8/20241598닷넷: 2228. .NET Profiler - IMetaDataEmit2::DefineMethodSpec 사용법
13575정성태3/7/20241705닷넷: 2227. 최신 C# 문법을 .NET Framework 프로젝트에 쓸 수 있을까요?
13574정성태3/6/20241613닷넷: 2226. C# - "Docker Desktop for Windows" Container 환경에서의 IPv6 DualMode 소켓
13573정성태3/5/20241580닷넷: 2225. Windbg - dumasync로 분석하는 async/await 호출
13572정성태3/4/20241669닷넷: 2224. C# - WPF의 Dispatcher Queue로 알아보는 await 호출의 hang 현상파일 다운로드1
13571정성태3/1/20241644닷넷: 2223. C# - await 호출과 WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13570정성태2/29/20241652닷넷: 2222. C# - WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13569정성태2/28/20241586닷넷: 2221. C# - LoadContext, LoadFromContext 그리고 GAC파일 다운로드1
13568정성태2/27/20241801닷넷: 2220. C# - .NET Framework 프로세스의 LoaderOptimization 설정을 확인하는 방법파일 다운로드1
13567정성태2/27/20241807오류 유형: 898. .NET Framework 3.5 이하에서 mscoree.tlb 참조 시 System.BadImageFormatException파일 다운로드1
13566정성태2/27/20241824오류 유형: 897. Windows 7 SDK 설치 시 ".NET Development" 옵션이 비활성으로 선택이 안 되는 경우
13565정성태2/23/20241687닷넷: 2219. .NET CLR2 보안 모델에서의 개별 System.Security.Permissions 제어
13564정성태2/22/20241913Windows: 259. Hyper-V Generation 1 유형의 VM을 Generation 2 유형으로 바꾸는 방법
13563정성태2/21/20241954디버깅 기술: 196. windbg - async/await 비동기인 경우 메모리 덤프 분석의 어려움
13562정성태2/21/20241977오류 유형: 896. ASP.NET - .NET Framework 기본 예제에서 System.Web에 대한 System.IO.FileNotFoundException 예외 발생
13561정성태2/20/20242051닷넷: 2218. C# - (예를 들어, Socket) 비동기 I/O에 대한 await 호출 시 CancellationToken을 이용한 취소파일 다운로드1
1  [2]  3  4  5  6  7  8  9  10  11  12  13  14  15  ...