Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)
(시리즈 글이 6개 있습니다.)
개발 환경 구성: 300. C# DLL에서 Win32 C/C++처럼 dllexport 함수를 제공하는 방법
; https://www.sysnet.pe.kr/2/0/11052

.NET Framework: 828. C# DLL에서 Win32 C/C++처럼 dllexport 함수를 제공하는 방법 - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/11884

개발 환경 구성: 466. C# DLL에서 Win32 C/C++처럼 dllexport 함수를 제공하는 방법 - 세 번째 이야기
; https://www.sysnet.pe.kr/2/0/12118

.NET Framework: 878. C# DLL에서 Win32 C/C++처럼 dllexport 함수를 제공하는 방법 - 네 번째 이야기(IL 코드로 직접 구현)
; https://www.sysnet.pe.kr/2/0/12120

.NET Framework: 880. C# - PE 파일로부터 IMAGE_COR20_HEADER 및 VTableFixups 테이블 분석
; https://www.sysnet.pe.kr/2/0/12126

.NET Framework: 881. C# DLL에서 제공하는 Win32 export 함수의 내부 동작 방식(VT Fix up Table)
; https://www.sysnet.pe.kr/2/0/12127




C# DLL에서 Win32 C/C++처럼 dllexport 함수를 제공하는 방법 - 두 번째 이야기

예전에 다뤘던 방법은,

C# DLL에서 Win32 C/C++처럼 dllexport 함수를 제공하는 방법
; https://www.sysnet.pe.kr/2/0/11052

UnmanagedExports라는 NuGet 패키지를 통해 가능했는데, 이번에 설명할 방법은 Microsoft.DotNet.ILCompiler에서 제공합니다.

Building Native Libraries with CoreRT
; https://github.com/dotnet/corert/tree/master/samples/NativeLibrary

Writing Native Libraries in C# and using them in other languages
; https://dev.to/encrypt0r/writing-native-libraries-in-c-3kl

현재 ILCompiler는 정규 nuget.org가 아닌 myget.org에서 배포하므로,

Microsoft.DotNet.ILCompiler v1.0.0-alpha-27527-01
; https://dotnet.myget.org/feed/dotnet-core/package/nuget/Microsoft.DotNet.ILCompiler

다음의 글에 설명했던 데로,

Visual Studio 없이 최신 C# (8.0) 컴파일러를 사용하는 방법
; https://www.sysnet.pe.kr/2/0/11834

feed 소스를 "https://dotnet.myget.org/F/dotnet-core/api/v3/index.json"로 설정한 항목을 추가해야 합니다.

cs_native_shared_2.png




그럼 예제를 다뤄볼까요? ^^

우선 .NET Core 라이브러리 프로젝트를 만들고 소스 코드를 다음과 같이 입력합니다.

using System;
using System.Runtime.InteropServices;

public class Class1
{
    [NativeCallable(EntryPoint = "add", CallingConvention = CallingConvention.StdCall)]
    public static int Add(int a, int b)
    {
        return a + b;
    }
}

namespace System.Runtime.InteropServices
{
    [AttributeUsage(AttributeTargets.Method)]
    public sealed class NativeCallableAttribute : Attribute
    {
        public string EntryPoint;
        public CallingConvention CallingConvention;
        public NativeCallableAttribute() { }
    }
}

NativeCallable 특성은 ILCompiler가 인식만 하면 되기 때문에 위와 같이 임의로 정의해서 포함하면 됩니다. 그다음, 현재의 라이브러리 프로젝트에 이전에 추가했던 "Pakcage source"로부터 Microsoft.DotNet.ILCompiler 패키지를 추가합니다.

cs_native_shared_3.png

Install-Package Microsoft.DotNet.ILCompiler -Version 1.0.0-alpha-27527-01

그럼, csproj에 다음의 설정이 추가됩니다.

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

  <PropertyGroup>
    <TargetFramework>netcoreapp2.1</TargetFramework>
    <Platforms>x64</Platforms>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.DotNet.ILCompiler" Version="1.0.0-alpha-27527-01" />
  </ItemGroup>

</Project>

위의 글은 더 이상 유효하지 않고, 이제 다음의 글에 따라 실습하시면 됩니다.

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

끝입니다. 이제 (비주얼 스튜디오가 아닌) 명령행에서 다음과 같이 빌드해 주면,

dotnet.exe publish /p:NativeLib=Shared -r win-x64 -c Release

x64 DLL이 다음의 경로에 생성됩니다.

...[project_path]...\bin\x64\Release\netcoreapp2.1\win-x64\native

그리고 이것을 depends.exe로 확인하면 다음과 같이 add 함수가 export 된 것을 확인할 수 있습니다.

cs_native_shared_1.png




그런데, 사실 많이 사용할 것 같지는 않습니다. 왜냐하면 이전에 설명한 UnmanagedExports는 비주얼 스튜디오에서 빌드하는 것만으로 DLL 생성이 되었던 반면 Microsoft.DotNet.ILCompiler의 경우에는 명령행에서 dotnet publish를 해야 하기 때문입니다. (게다가 비주얼 스튜디오에서의 publish 명령도 일반적인 managed DLL을 생성할 뿐입니다.) 따라서 매우 번거로운 절차로 인해 차라리 UnmanagedExports를 사용하게 될 것입니다.




참고로, 현재 64비트 DLL만 제공할 뿐 32비트 DLL을 생성하려는 경우 다음과 같이 오류 메시지가 발생합니다.

C:\temp> dotnet publish /p:NativeLib=Shared -r win-x86 -c Release
Microsoft (R) Build Engine version 16.0.385-preview+g966cdf2ac6 for .NET Core
Copyright (C) Microsoft Corporation. All rights reserved.

Restoring packages for C:\temp\ClassLibrary1\ClassLibrary1.csproj...
Installing runtime.win-x86.Microsoft.NETCore.DotNetAppHost 2.1.0.
Installing runtime.win-x86.Microsoft.NETCore.DotNetHostResolver 2.1.0.
Installing runtime.win-x86.Microsoft.NETCore.DotNetHostPolicy 2.1.0.
Installing runtime.win-x86.Microsoft.NETCore.App 2.1.0.
Restore completed in 14.69 sec for C:\temp\ClassLibrary1\ClassLibrary1.csproj.
C:\Program Files (x86)\dotnet\sdk\3.0.100-preview-010184\Sdks\Microsoft.NET.Sdk\targets\Microsoft.NET.RuntimeIdentifierInference.targets(151,5): message NETSDK1057: You are using a preview version of .NET Core. See: https://aka.ms/dotnet-core-preview [C:\temp\ClassLibrary1\ClassLibrary1.csproj]
ClassLibrary1 -> C:\temp\ClassLibrary1\bin\Release\netcoreapp2.1\win-x86\ClassLibrary1.dll
%USERPROFILE%\.nuget\packages\microsoft.dotnet.ilcompiler\1.0.0-alpha-27527-01\build\Microsoft.NETCore.Native.Publish.targets(76,5): error : win-x86 not supported yet. https://github.com/dotnet/corert/issues/4589 [C:\temp\ClassLibrary1\ClassLibrary1.csproj]


또한, Microsoft.DotNet.ILCompiler의 경우 현재 명령행(cmd.exe)의 Visual C++ 빌드 환경을 사용하기 때문에 "Developer Command Prompt for VS 2019"라는 제목의 명령행 환경에서 빌드하면 다음과 같은 식의 오류가 발생합니다.

C:\temp> dotnet publish /p:NativeLib=Shared -r win-x64 -c Release
Microsoft (R) Build Engine version 16.0.385-preview+g966cdf2ac6 for .NET Core
Copyright (C) Microsoft Corporation. All rights reserved.

  Restore completed in 22.07 ms for C:\temp\ClassLibrary1\ClassLibrary1.csproj.
C:\Program Files\dotnet\sdk\3.0.100-preview-010184\Sdks\Microsoft.NET.Sdk\targets\Microsoft.NET.RuntimeIdentifierInference.targets(151,5): message NETSDK1057: You are using a preview version of .NET Core. See: https://aka.ms/dotnet-core-preview [C:\temp\ClassLibrary1\ClassLibrary1.csproj]
  ClassLibrary1 -> C:\temp\ClassLibrary1\bin\Release\netcoreapp2.1\win-x64\ClassLibrary1.dll
  Generating compatible native code. To optimize for size or speed, visit https://aka.ms/OptimizeCoreRT
libcpmt.lib(nothrow.obj) : fatal error LNK1112: module machine type 'x86' conflicts with target machine type 'x64' [C:\temp\ClassLibrary1\ClassLibrary1.csproj]
%USERPROFILE%\.nuget\packages\microsoft.dotnet.ilcompiler\1.0.0-alpha-27527-01\build\Microsoft.NETCore.Native.targets(333,5): error MSB3073: The command "link  @"obj\Release\netcoreapp2.1\win-x64\native\link.rsp"" exited with code 1112. [C:\temp\ClassLibrary1\ClassLibrary1.csproj]

왜냐하면 "Developer Command Prompt for VS 2019" 명령행 환경은 x86이기 때문인데, 이 문제를 해결하려면 "x64 Native Tools Command Prompot for VS 2019"라는 이름의 메뉴를 실행해 그 cmd.exe 환경에서 "dotnet publish ..." 명령을 실행해야 합니다. 아니면, x86 빌드 환경에서도 그냥 "x64 Native Tools Command Prompot for VS 2019"가 호출하는 배치 파일을 실행해 x64 환경으로 바꾸면 됩니다.

C:\temp\ClassLibrary1\ClassLibrary2> "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Auxiliary\Build\vcvars64.bat"
**********************************************************************
** Visual Studio 2019 Developer Command Prompt v16.8.0
** Copyright (c) 2020 Microsoft Corporation
**********************************************************************
[vcvarsall.bat] Environment initialized for: 'x64'

C:\temp\ClassLibrary1\ClassLibrary2> dotnet publish /p:NativeLib=Shared -r win-x64 -c Release
Microsoft (R) Build Engine version 16.8.0+126527ff1 for .NET
Copyright (C) Microsoft Corporation. All rights reserved.

  Determining projects to restore...
  All projects are up-to-date for restore.
  ClassLibrary2 -> C:\temp\ClassLibrary1\ClassLibrary2\bin\x64\Release\netcoreapp3.1\win-x64\ClassLibrary2.dll
  Generating compatible native code. To optimize for size or speed, visit https://aka.ms/OptimizeCoreRT
     Creating library bin\x64\Release\netcoreapp3.1\win-x64\native\ClassLibrary2.lib and object bin\x64\Release\netcoreapp3.1\win-x64\native\ClassLibrary2.exp
  ClassLibrary2 -> C:\temp\ClassLibrary1\ClassLibrary2\bin\x64\Release\netcoreapp3.1\win-x64\publish\

마지막으로, 다음과 같이 오류가 발생할 수도 있습니다.

C:\temp\demo_code\nativeLib> dotnet publish /p:NativeLib=Shared -r win-x64 -c release -o win-x64-shared
Microsoft (R) Build Engine version 16.8.0+126527ff1 for .NET
Copyright (C) Microsoft Corporation. All rights reserved.

  Determining projects to restore...
  Restored C:\temp\demo_code\nativeLib\nativeLib.csproj (in 1.58 min).
  nativeLib -> C:\temp\demo_code\nativeLib\bin\release\net5.0\win-x64\nativeLib.dll
C:\Users\testusr\.nuget\packages\microsoft.dotnet.ilcompiler\1.0.0-alpha-29408-02\build\Microsoft.NETCore.Native.Windows.props(109,5): error : Platform linker not found. To fix this problem, download and install Visual Studio 2017 from http://visualstudio.com. Make sure to install the Desktop Development for C++ workload. [C:\temp\demo_code\nativeLib\nativeLib.csproj]

오류 메시지에 따라, 해당 컴퓨터에는 Visual C++ 개발환경이 설치되어 있지 않기 때문입니다. 만약 비주얼 스튜디오가 설치된 상태라면 C++ 쪽 구성 요소를 추가하면 되고, 그렇지 않다면 Build Tools for Visual Studio 2019를 다운로드하면 됩니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 11/17/2020]

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)
13344정성태5/9/20236306.NET Framework: 2116. C# - OpenAI API 사용 - 지원 모델 목록 [1]파일 다운로드1
13343정성태5/9/20234196디버깅 기술: 192. Windbg - Hyper-V VM으로 이더넷 원격 디버깅 연결하는 방법
13342정성태5/8/20234120.NET Framework: 2115. System.Text.Json의 역직렬화 시 필드/속성 주의
13341정성태5/8/20233904닷넷: 2114. C# 12 - 모든 형식의 별칭(Using aliases for any type)
13340정성태5/8/20233905오류 유형: 857. Microsoft.Data.SqlClient.SqlException - 0x80131904
13339정성태5/6/20234612닷넷: 2113. C# 12 - 기본 생성자(Primary Constructors)
13338정성태5/6/20234097닷넷: 2112. C# 12 - 기본 람다 매개 변수파일 다운로드1
13337정성태5/5/20234615Linux: 59. dockerfile - docker exec로 container에 접속 시 자동으로 실행되는 코드 적용
13336정성태5/4/20234372.NET Framework: 2111. C# - 바이너리 출력 디렉터리와 연관된 csproj 설정
13335정성태4/30/20234501.NET Framework: 2110. C# - FFmpeg.AutoGen 라이브러리를 이용한 기본 프로젝트 구성 - Windows Forms파일 다운로드1
13334정성태4/29/20234150Windows: 250. Win32 C/C++ - Modal 메시지 루프 내에서 SetWindowsHookEx를 이용한 Thread 메시지 처리 방법
13333정성태4/28/20233623Windows: 249. Win32 C/C++ - 대화창 템플릿을 런타임에 코딩해서 사용파일 다운로드1
13332정성태4/27/20233718Windows: 248. Win32 C/C++ - 대화창을 위한 메시지 루프 사용자 정의파일 다운로드1
13331정성태4/27/20233741오류 유형: 856. dockerfile - 구 버전의 .NET Core 이미지 사용 시 apt update 오류
13330정성태4/26/20233408Windows: 247. Win32 C/C++ - CS_GLOBALCLASS 설명
13329정성태4/24/20233621Windows: 246. Win32 C/C++ - 직접 띄운 대화창 템플릿을 위한 Modal 메시지 루프 생성파일 다운로드1
13328정성태4/19/20233254VS.NET IDE: 184. Visual Studio - Fine Code Coverage에서 동작하지 않는 Fake/Shim 테스트
13327정성태4/19/20233676VS.NET IDE: 183. C# - .NET Core/5+ 환경에서 Fakes를 이용한 단위 테스트 방법
13326정성태4/18/20235045.NET Framework: 2109. C# - 닷넷 응용 프로그램에서 SQLite 사용 (System.Data.SQLite) [1]파일 다운로드1
13325정성태4/18/20234392스크립트: 48. 파이썬 - PostgreSQL의 with 문을 사용한 경우 연결 개체 누수
13324정성태4/17/20234234.NET Framework: 2108. C# - Octave의 "save -binary ..."로 생성한 바이너리 파일 분석파일 다운로드1
13323정성태4/16/20234132개발 환경 구성: 677. Octave에서 Excel read/write를 위한 io 패키지 설치
13322정성태4/15/20234897VS.NET IDE: 182. Visual Studio - 32비트로만 빌드된 ActiveX와 작업해야 한다면?
13321정성태4/14/20233733개발 환경 구성: 676. WSL/Linux Octave - Python 스크립트 연동
13320정성태4/13/20233739개발 환경 구성: 675. Windows Octave 8.1.0 - Python 스크립트 연동
13319정성태4/12/20234171개발 환경 구성: 674. WSL 2 환경에서 GNU Octave 설치
1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...