Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

Visual Studio에서 직접 컴파일하는 IL 언어 확장 도구 - IL Support

물리적인 머신에 들어가는 CPU가 기계어를 해석하고, 그 기계어에 거의 1:1 매핑을 시켜 만든 언어가 바로 "어셈블리(Assembly)" 입니다. (닷넷의 배포단위인 '어셈블리'와 혼동하시면 안됩니다.)

그리고, JVM과 CLR은 일종의 가상머신입니다. 따라서 각각의 가상머신 환경에도 기계어 레벨에 대응하는 표현이 있는데 자바의 경우 Byte Code, 닷넷은 IL(Intermediate Language)이 됩니다. 그렇다면 기계어와 대응되는 어셈블리가 언어가 있었던 것처럼 JVM/CLR 가상머신에서도 그와 같은 언어가 있지 않을까요?

맞습니다. 자바라면 Jasmine이 있고, 닷넷에는 "IL 언어"가 있습니다. 가령 IL 언어로 Hello World 프로그램을 만들면 다음과 같이 코딩을 할 수 있습니다.

[소스 코드 1]

.assembly extern mscorlib
{
  .publickeytoken = (B7 7A 5C 56 19 34 E0 89 )                        
  .ver 4:0:0:0
}

.assembly ConsoleApplication1
{
  .hash algorithm 0x00008004
  .ver 1:0:0:0
}

.module ConsoleApplication1.exe
.imagebase 0x00400000
.file alignment 0x00000200
.stackreserve 0x00100000
.subsystem 0x0003       
.corflags 0x00000001    

.class private auto ansi beforefieldinit Program
       extends [mscorlib]System.Object
{
  .method private hidebysig static void  Main(string[] args) cil managed
  {
    .entrypoint
    // Code size       13 (0xd)
    .maxstack  8
    IL_0000:  nop
    IL_0001:  ldstr      "Hello World"
    IL_0006:  call       void [mscorlib]System.Console::WriteLine(string)
    IL_000b:  nop
    IL_000c:  ret
  }
}

이 때문에 닷넷 환경에서 실행되는 언어를 만드는 개발자가 있다면 2가지 방법으로 가능합니다.

  1. 직접 PE 포맷을 따르는 닷넷 모듈을 출력하는 컴파일러 개발
  2. IL 언어로 변환하는 컴파일러 개발, PE 포맷의 모듈은 ilasm.exe에게 대행

예를 들어, 제가 Output 함수만 제공하는 새로운 K#이라는 언어를 만들었다면,

// K# 언어 사용법
// Output 함수 뒤에 출력할 문자열 지정, 그외 기능은 없음!

Output "TEST"

이 소스코드를 컴파일하는 KSC.exe 컴파일러 프로그램은 단지 "[소스 코드 1]"에서 살펴봤던 IL 텍스트 출력의 "Hello World" 문자열만 "TEST"로 바꿔 파일로 저장한 다음 ilasm.exe에 의해 닷넷 모듈로 컴파일하는 방법을 선택할 수 있습니다.

이 방법이 꽤나 현실성이 있는 이유가, 모든 닷넷 프레임워크는 기본적으로 ilasm.exe를 함께 설치해 주기 때문입니다.

새로운 닷넷 언어 만들기 참 쉽죠??? ^^




어쨌든, 그런 IL 언어를 다루려면 기존에는 명령행 창(cmd.exe)에서 ilasm.exe와 ildasm.exe를 이용해야만 했는데 아래의 도구를 사용하면 Visual Studio에서 IL 언어를 직접 다루는 프로젝트를 생성할 수 있습니다.

IL Support
; http://visualstudiogallery.msdn.microsoft.com/44034a7b-143d-4b51-b7bc-99aa656ba137

Moving Memory in .NET using VB and the CIL
; http://www.codeproject.com/Articles/767624/Moving-Memory-in-NET-using-VB-and-the-CIL

아쉽게도 Visual Studio 2010, 2012에서만 설치가 되는데요. "Tools" / "Extension Manager..." 메뉴를 선택하고 다음과 같이 "Online Gallery"에서 "IL Support"로 검색하면 찾을 수 있습니다.

il_support_1.png

설치하고 나면, 다음과 같이 "IL Support" 관련 프로젝트 템플릿이 생성되고,

il_support_2.png

기본 제공되는 Program.cs 파일에는 IL 언어에 정의되는 메서드로 실행을 전달하는 MethodImplOptions.ForwardRef 특성이 정의된 선언이 있고,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
        }

        [MethodImpl(MethodImplOptions.ForwardRef)]
        public static extern int Square(int number);
    }
}

함께 제공되는 Program.il 파일에 코드를 담은 Square 메서드가 IL 언어로 정의되어 있습니다.

.class public ConsoleApplication2.Program
{
    .method public static int32 Square(int32 number) cil managed
    {
        .maxstack 2
        ldarg.0
        dup
        mul
        ret
    }
}

재치있군요. ^^ 별로 쓸모없을 것 같았던 MethodImpl 특성의 MethodImplOptions.ForwardRef 옵션을 이용해서 멋지게 C# 프로젝트와 통합을 시켰습니다.

물론, Hello World를 출력하는 우리의 함수를 다음과 같이 추가할 수도 있습니다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            HelloWorld();
        }

        [MethodImpl(MethodImplOptions.ForwardRef)]
        public static extern int Square(int number);

        [MethodImpl(MethodImplOptions.ForwardRef)]
        public static extern void HelloWorld();
    }
}

.class public ConsoleApplication2.Program
{
    .method public static int32 Square(int32 number) cil managed
    {
        .maxstack 2
        ldarg.0
        dup
        mul
        ret
    }

    .method public static void HelloWorld() cil managed
    {
        .maxstack  8
        IL_0000:  nop
        IL_0001:  ldstr      "Hello World"
        IL_0006:  call       void [mscorlib]System.Console::WriteLine(string)
        IL_000b:  nop
        IL_000c:  ret
    }
}

비록, IL 언어를 직접적으로 쓸 일이 거의 없지만... 이것으로 비로소 "IL 언어"도 Visual Studio가 지원하는 ".NET 호환 언어"로써의 반열에 오르게 되는군요. ^^ (애석하게도 intellisense같은 기능은 없지만!)

참고로, 갤러리에는 올라오지 않았지만 현재 Visual Studio 2013을 지원하는 소스코드로는 업데이트되었습니다.

 hross/ILSupport 
 ; https://github.com/hross/ILSupport




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 6/22/2014]

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)
13515정성태1/6/20242621닷넷: 2195. async 메서드 내에서 C# 7의 discard 구문 활용 사례 [1]
13514정성태1/5/20242307개발 환경 구성: 702. IIS - AppPool의 "Disable Overlapped Recycle" 옵션
13513정성태1/5/20242223닷넷: 2194. C# - WebActivatorEx / System.Web의 PreApplicationStartMethod 특성
13512정성태1/4/20242176개발 환경 구성: 701. IIS - w3wp.exe 프로세스의 ASP.NET 런타임을 항상 Warmup 모드로 유지하는 preload Enabled 설정
13511정성태1/4/20242198닷넷: 2193. C# - ASP.NET Web Application + OpenAPI(Swashbuckle) 스펙 제공
13510정성태1/3/20242120닷넷: 2192. C# - 특정 실행 파일이 있는지 확인하는 방법 (Linux)
13509정성태1/3/20242169오류 유형: 887. .NET Core 2 이하의 프로젝트에서 System.Runtime.CompilerServices.Unsafe doesn't support netcoreapp2.0.
13508정성태1/3/20242220오류 유형: 886. ORA-28000: the account is locked
13507정성태1/2/20242867닷넷: 2191. C# - IPGlobalProperties를 이용해 netstat처럼 사용 중인 Socket 목록 구하는 방법파일 다운로드1
13506정성태12/29/20232461닷넷: 2190. C# - 닷넷 코어/5+에서 달라지는 System.Text.Encoding 지원
13505정성태12/27/20232990닷넷: 2189. C# - WebSocket 클라이언트를 닷넷으로 구현하는 예제 (System.Net.WebSockets)파일 다운로드1
13504정성태12/27/20232579닷넷: 2188. C# - ASP.NET Core SignalR로 구현하는 채팅 서비스 예제파일 다운로드1
13503정성태12/27/20232443Linux: 67. WSL 환경 + mlocate(locate) 도구의 /mnt 디렉터리 검색 문제
13502정성태12/26/20232564닷넷: 2187. C# - 다른 프로세스의 환경변수 읽는 예제파일 다운로드1
13501정성태12/25/20232325개발 환경 구성: 700. WSL + uwsgi - IPv6로 바인딩하는 방법
13500정성태12/24/20232416디버깅 기술: 194. Windbg - x64 가상 주소를 물리 주소로 변환
13498정성태12/23/20233102닷넷: 2186. 한국투자증권 KIS Developers OpenAPI의 C# 래퍼 버전 - eFriendOpenAPI NuGet 패키지
13497정성태12/22/20232496오류 유형: 885. Visual Studiio - error : Could not connect to the remote system. Please verify your connection settings, and that your machine is on the network and reachable.
13496정성태12/21/20232490Linux: 66. 리눅스 - 실행 중인 프로세스 내부의 환경변수 설정을 구하는 방법 (gdb)
13495정성태12/20/20232417Linux: 65. clang++로 공유 라이브러리의 -static 옵션 빌드가 가능할까요?
13494정성태12/20/20232591Linux: 64. Linux 응용 프로그램의 (C++) so 의존성 줄이기(ReleaseMinDependency) - 두 번째 이야기
13493정성태12/19/20232721닷넷: 2185. C# - object를 QueryString으로 직렬화하는 방법
13492정성태12/19/20232394개발 환경 구성: 699. WSL에 nopCommerce 예제 구성
13491정성태12/19/20232269Linux: 63. 리눅스 - 다중 그룹 또는 사용자를 리소스에 권한 부여
13490정성태12/19/20232399개발 환경 구성: 698. Golang - GLIBC 의존을 없애는 정적 빌드 방법
13489정성태12/19/20232178개발 환경 구성: 697. GoLand에서 ldflags 지정 방법
1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...