티스토리 뷰

unsafe keyword를 사용하면 , C/C++에서 사용하는 pointer를 C#에서도 사용할 수 있다.


unsafe keyword를 사용하기 위해서 compile할 때 /unsafe option을 주어야한다.


compile할 때 /unsafe option을 주려면 Visual Studio에서 아래와 같이 설정해주면 된다.


참고 : /unsafe (C# Compiler Options)


To set /unsafe compiler option in the Visual Studio development environment

    1. Open the project's Properties page.
    2. Click the Build property page.
    3. Select the Allow Unsafe Code check box.


아래는 pointer를 사용하는 간단한 C++ 예제이다.

#include <iostream>
#include <cstdlib>

using namespace std;

int main() {
int x;
int *p;

x = 1;
p = &x;

cout << "Before Modification:" << endl;
cout << "x is " << x << ", *p is " << *p << endl;
cout << "&x is " << &x << ", p is " << p << endl;

*p = 2;

cout << "After Modification:" << endl;
cout << "x is " << x << ", *p is " << *p << endl;
cout << "&x is " << &x << ", p is " << p << endl;

return EXIT_SUCCESS;
}

위 예제의 출력 결과는 아래와 같다.


Before Modification:

x is 1, *p is 1

&x is 0x61ff08, p is 0x61ff08

After Modification:

x is 2, *p is 2

&x is 0x61ff08, p is 0x61ff08


pointer variable인 p를 이용해서 int variable인 x의 값을 바꾸었다.


pointer variable인 p에는 x의 address가 저장된다.


두 변수의 값을 서로 swap해주는 예제는 pointer를 사용하는 대표적인 예제이다.


아래는 C++로 된 간단한 swap 예제이다.

#include <cstdlib>
#include <iostream>

void swap(int *a, int *b);

using namespace std;

int main() {
int x = 1, y = 2;
swap(&x, &y);
cout << "x is " << x << ", y is " << y << endl;
return EXIT_SUCCESS;
}

void swap(int *a, int *b) {
int temp;
temp = *a;
*a = *b;
*b = temp;
}

출력 결과는 아래와 같다.


x is 2, y is 1


x와 y의 값이 서로 바뀌었다.


이것을 unsafe keyword와 pointer를 사용해서 C#으로 구현해보자.


아래는 C# 예제이다.

using System;

namespace Console1 {
class Program {
static void Main(string[] args) {
int x = 1, y = 2;

unsafe {
Swap(&x, &y);
}

Console.WriteLine($"x is {x}, y is {y}");
}

static unsafe void Swap(int* a, int* b) {
int temp;
temp = *a;
*a = *b;
*b = temp;
}
}
}

unsafe keyword를 사용한 부분을 눈여겨보기 바란다.


출력 결과는 아래와 같다.


x is 2, y is 1


공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함