본문 바로가기

프로그래밍/C#

C# unsafe 와 fixed (포인터 안전하게 사용하기 char*, int* 등등..)

 

 

C# 에서도 C++ 처럼 type* 등 포인터를 사용 할 수 있다.

C#에서는 이런걸 unsafe 코드라고 부른다.

가비지 콜렉터 설명할때 나왔었는데... CLR에서 메모리 관리를 하는데 *을 사용함으로써 메모리를 직접 건드리는것은 매우 위험하다 =ㅁ=

*을 사용하는 코드를 작성하려면 컴파일 옵션으로 /unsafe 를 사용해야 한다.

 

아래 이미지 보고 참고하면 됨

프로젝트 속성 -> 빌드 -> unsafe code 에 체크 해줘야지만 빌드 에러없이 실행 할 수 있다.

 

 

 

 

이렇게 unsafe 코드를 작성하면.. CLR에서 언제 메모리정리를 하면서 이동시킬지 모르기 때문에

저 포인터 주소는 믿을수 없다.. 런타임 에러가 빵빵 터질지도 ㅡ.ㅡ.

그래서 unsafe 코드는 fixed 와 함께 사용하여야만 한다!

fixed는 메모리를 고정 시켜주기 때문에 unsafe 와 함께 사용하면 안전하게 쓸 수 있다.

fixed 는 unsafe 코드 내에서만 사용 가능하다

fixed 스코프를 나오면 메모리 고정은 끝난다.

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestD
{
    class Program
    {
        class Point
        {
            public int X;
            public int Y;
        }
        unsafe static void CallByPoint(int* x)
        {
            *x = 10;
        }
        static void Main(string[] args)
        {
            Point pos = new Point();
            unsafe
            {
                fixed(int* fixedX = &pos.X)
                {
                    CallByPoint(fixedX);
                }
            }

            Console.WriteLine("Call-By-Poing:{0}", pos.X);
        }
    }
}

 

 

 

 

 

 

 

 

 

 

.