본문 바로가기

Programming Language/MSIL

MSIL로 입출력하기 및 박싱/언박싱

336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.
//test2.il
.assembly extern mscorlib
{
}

.assembly Test
{
}

.module test.exe

.method static public void main() il managed
{
	.entrypoint
	.maxstack 16

	/* 이 곳에 지역 변수를 선언합니다. */
	.locals init([0] string temp, [1] int32 a, [2] int32 b, [3] int32 result)

	/* System.Console.Write("Input the 1st integer : "); */
	ldstr "Input the 1st integer : "
	call void [mscorlib]System.Console::Write(string)

	/* temp = System.Console.ReadLine(); */
	call string [mscorlib]System.Console::ReadLine()
	stloc.0

	/* a = System.Int32.Parse(temp) */
	ldloc.0
	call int32 [mscorlib]System.Int32::Parse(string)
	stloc.1

	/* System.Console.Write("Input the 2nd integer : "); */
	ldstr "Input the 2nd integer : "
	call void [mscorlib]System.Console::Write(string)

	/* temp = System.Console.ReadLine(); */
	call string [mscorlib]System.Console::ReadLine()
	stloc.0

	/* b = System.Int32.Parse(temp) */
	ldloc.0
	call int32 [mscorlib]System.Int32::Parse(string)
	stloc.2

	/* result = a + b; */
	ldloc.1
	ldloc.2
	add
	stloc.3

	/* System.Console.WriteLine("{0} + {1} = {2}", a, b, result); */
	ldstr "{0} + {1} = {2}"
	ldloc.1
	box int32
	ldloc.2
	box int32
	ldloc.3
	box int32
	call void [mscorlib]System.Console::WriteLine(string, object, object, object)

	ret
}

두 수를 입력받아 그 합을 구하는 예제입니다.



여기에서 눈여겨 볼 명령은 add, stloc, ldloc, box입니다.

add 명령은 스택에 push한 연속된 두 수를 더하라는 뜻을 가지고 있습니다. 더한 결과는 스택의 최상단에 push됩니다. 예를 들어 두 수 A와 B를 더한 값을 원한다면

ldXXX [더할 수 A]
ldXXX [더할 수 B]
add

이렇게 3줄로 표현됩니다.

stloc은 스택의 최상단에 있는 값을 지역변수로 가져오는 뜻입니다. 대상이 될 수 있는 지역변수는 3번까지이며, stloc.0, stloc.1, stloc.2, stloc.3의 4가지 명령이 존재합니다. 예를 들어 "stloc.0"이라 하면 스택의 최상단에 있는 값을 첫 번째로 선언된 지역변수로 가져오라는 뜻이 됩니다. 4번째로 선언된 지역변수부터는 피리어드(.) 없이 사용합니다. 예를 들어 "stloc 10"이라 하면 10번째로 선언된 지역변수로 스택의 값을 pop하라는 뜻이 됩니다. 이렇게 명령어가 따로 구분된 이유는 명령어의 크기를 작게하기 위해서입니다. 실제로 stloc.0부터 stloc.3은 명령어가 1바이트이지만, "stloc n"은 명령어가 2바이트를 차지합니다.

ldloc은 지역변수에 있는 값을 연산을 위해 스택으로 내보내라는 뜻입니다. 마찬가지로 1바이트 명령어로 ldloc.0부터 ldloc.3까지가 따로 마련되어 있습니다.

box는 값 형식을 System.Object 형으로 박싱하는 명령입니다. 형식은 다음과 같습니다.

ldXXX [박싱할 값 형식]
box [원래 자료형]


'Programming Language > MSIL' 카테고리의 다른 글

MSIL의 기본 자료형  (0) 2014.07.27
MSIL로 닷넷 프로그램 작성하기  (0) 2014.07.26