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

비밀번호

댓글 작성자
 




... 16  17  18  19  20  21  [22]  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13071정성태6/9/20227231스크립트: 39. Python에서 cx_Oracle 환경 구성
13070정성태6/8/20227045오류 유형: 813. Windows 11에서 입력 포커스가 바뀌는 문제 [1]
13069정성태5/26/20229276.NET Framework: 2019. C# - .NET에서 제공하는 3가지 Timer 비교 [2]
13068정성태5/24/20227734.NET Framework: 2018. C# - 일정 크기를 할당하는 동안 GC를 (가능한) 멈추는 방법 [1]파일 다운로드1
13067정성태5/23/20227102Windows: 206. Outlook - 1년 이상 지난 메일이 기본적으로 안 보이는 문제
13066정성태5/23/20226411Windows: 205. Windows 11 - Windows + S(또는 Q)로 뜨는 작업 표시줄의 검색 바가 동작하지 않는 경우
13065정성태5/20/20227084.NET Framework: 2017. C# - Windows I/O Ring 소개 [2]파일 다운로드1
13064정성태5/18/20226650.NET Framework: 2016. C# - JIT 컴파일러의 인라인 메서드 처리 유무
13063정성태5/18/20227070.NET Framework: 2015. C# - 인라인 메서드(inline methods)
13062정성태5/17/20227859.NET Framework: 2014. C# - async/await 그리고 스레드 (4) 비동기 I/O 재현파일 다운로드1
13061정성태5/16/20226672.NET Framework: 2013. C# - FILE_FLAG_OVERLAPPED가 적용된 파일의 읽기/쓰기 시 Position 관리파일 다운로드1
13060정성태5/15/20229113.NET Framework: 2012. C# - async/await 그리고 스레드 (3) Task.Delay 재현파일 다운로드1
13059정성태5/14/20227609.NET Framework: 2011. C# - CLR ThreadPool의 I/O 스레드에 작업을 맡기는 방법 [1]파일 다운로드1
13058정성태5/13/20227533.NET Framework: 2010. C# - ThreadPool.SetMaxThreads 사용법
13057정성태5/12/20229206오류 유형: 812. 파이썬 - ImportError: cannot import name ...
13056정성태5/12/20226373.NET Framework: 2009. C# - async/await 그리고 스레드 (2) MyTask의 호출 흐름 [2]파일 다운로드1
13055정성태5/11/20229265.NET Framework: 2008. C# - async/await 그리고 스레드 (1) MyTask로 재현 [11]파일 다운로드1
13054정성태5/11/20226787.NET Framework: 2007. C# - 10진수 숫자를 담은 문자열을 숫자로 변환하는 방법 [11]파일 다운로드1
13053정성태5/10/20226420.NET Framework: 2006. C# - GC.KeepAlive 메서드의 역할
13052정성태5/9/20226429.NET Framework: 2005. C# - 생성한 참조 개체가 언제 GC의 정리 대상이 될까요?
13051정성태5/8/20226382.NET Framework: 2004. C# XingAPI - ACF 검색 결과로 구한 CSV 파일을 통해 퀀트 종목 찾기파일 다운로드1
13050정성태5/6/20226398.NET Framework: 2003. C# - COM 개체의 이벤트 핸들러에서 발생하는 예외에 대한 CLR의 특별 대우파일 다운로드1
13049정성태5/6/20225374오류 유형: 811. GoLand - Error: Cannot find package
13048정성태5/6/20226500오류 유형: 810. "ASUS TUF GAMING B550M-PLUS (WI-FI)" 모델에서 블루투스 장치가 인식이 안 되는 문제
13047정성태5/6/20226485오류 유형: 809. Speech Recognition could not start
13046정성태5/5/20226776.NET Framework: 2002. C# XingAPI - ACF 파일을 이용한 퀀트 종목 찾기(t1857)
... 16  17  18  19  20  21  [22]  23  24  25  26  27  28  29  30  ...