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)
13485정성태12/15/20232102오류 유형: 883. dotnet build/restore - error : Root element is missing
13484정성태12/14/20232179개발 환경 구성: 694. Windows 디렉터리 경로를 WSL의 /mnt 포맷으로 구하는 방법
13483정성태12/14/20232321닷넷: 2184. C# - 하나의 resource 파일을 여러 프로그램에서 (AOT 시에도) 사용하는 방법파일 다운로드1
13482정성태12/13/20232923닷넷: 2183. C# - eFriend Expert OCX 예제를 .NET Core/5+ Console App에서 사용하는 방법 [2]파일 다운로드1
13481정성태12/13/20232297개발 환경 구성: 693. msbuild - .NET Core/5+ 프로젝트에서 resgen을 이용한 리소스 파일 생성 방법파일 다운로드1
13480정성태12/12/20232678개발 환경 구성: 692. Windows WSL 2 + Chrome 웹 브라우저 설치
13479정성태12/11/20232356개발 환경 구성: 691. WSL 2 (Ubuntu) + nginx 환경 설정
13477정성태12/8/20232564닷넷: 2182. C# - .NET 7부터 추가된 Int128, UInt128 [1]파일 다운로드1
13476정성태12/8/20232281닷넷: 2181. C# - .NET 8 JsonStringEnumConverter의 AOT를 위한 개선파일 다운로드1
13475정성태12/7/20232357닷넷: 2180. .NET 8 - 함수 포인터에 대한 Reflection 정보 조회파일 다운로드1
13474정성태12/6/20232205개발 환경 구성: 690. 닷넷 코어/5+ 버전의 ilasm/ildasm 실행 파일 구하는 방법 - 두 번째 이야기
13473정성태12/5/20232421닷넷: 2179. C# - 값 형식(Blittable)을 메모리 복사를 이용해 바이트 배열로 직렬화/역직렬화파일 다운로드1
13472정성태12/4/20232224C/C++: 164. Visual C++ - InterlockedCompareExchange128 사용 방법
13471정성태12/4/20232308Copilot - To enable GitHub Copilot, authorize this extension using GitHub's device flow
13470정성태12/2/20232623닷넷: 2178. C# - .NET 8부터 COM Interop에 대한 자동 소스 코드 생성 도입파일 다운로드1
13469정성태12/1/20232363닷넷: 2177. C# - (Interop DLL 없이) CoClass를 이용한 COM 개체 생성 방법파일 다운로드1
13468정성태12/1/20232306닷넷: 2176. C# - .NET Core/5+부터 달라진 RCW(Runtime Callable Wrapper) 대응 방식파일 다운로드1
13467정성태11/30/20232379오류 유형: 882. C# - Unhandled exception. System.Runtime.InteropServices.COMException (0x800080A5)파일 다운로드1
13466정성태11/29/20232554닷넷: 2175. C# - DllImport 메서드의 AOT 지원을 위한 LibraryImport 옵션
13465정성태11/28/20232309개발 환경 구성: 689. MSBuild - CopyToOutputDirectory가 "dotnet publish" 시에는 적용되지 않는 문제파일 다운로드1
13464정성태11/28/20232438닷넷: 2174. C# - .NET 7부터 UnmanagedCallersOnly 함수 export 기능을 AOT 빌드에 통합파일 다운로드1
13463정성태11/27/20232379오류 유형: 881. Visual Studio - NU1605: Warning As Error: Detected package downgrade
13462정성태11/27/20232394오류 유형: 880. Visual Studio - error CS0246: The type or namespace name '...' could not be found
13461정성태11/26/20232423닷넷: 2173. .NET Core 3/5+ 기반의 COM Server를 registry 등록 없이 사용하는 방법파일 다운로드1
13460정성태11/26/20232367닷넷: 2172. .NET 6+ 기반의 COM Server 내에 Type Library를 내장하는 방법파일 다운로드1
13459정성태11/26/20232347닷넷: 2171. .NET Core 3/5+ 기반의 COM Server를 기존의 regasm처럼 등록하는 방법파일 다운로드1
1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...