티스토리 뷰
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
- Open the project's Properties page.
- Click the Build property page.
- 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
'Piece' 카테고리의 다른 글
Basic Structure [Python] __name__, __main__, import (0) | 2019.04.23 |
---|---|
[Python] virtualenv or venv (0) | 2018.12.26 |
From C# Call C++ [Hybrid] Mixing Sample (0) | 2018.07.21 |
[SQL Server] Enable TCP/IP Protocol & Port (0) | 2018.07.09 |
[Visual Studio] Dynamic/Static Library Setup Example using MySQL Connector/C++ (0) | 2018.07.09 |