C# - 포인터를 쓰는 경우 VerificationException이 발생한다면?
다음과 같이 포인터를 쓰는 경우,
unsafe int FloatToIntBytes(float value)
{
int* pBytes = (int*)&value;
return *pBytes;
}
이런 예외가 발생한다면?
+ e {System.Security.VerificationException: Operation could destabilize the runtime.
at MyTestClass.FloatToIntBytes(Single value)
at MyTestClass.Main()} System.Exception {System.Security.VerificationException}
아마도 여러분은 .NET 4.0에서 APTCA를 설정한 GAC 어셈블리를 만들고 있는 중일 것입니다. 이에 관한 자세한 설명은 다음의 글을 참고하시고.
.NET CLR4 보안 모델 - 3. CLR4 보안 모델에서의 APTCA 역할
; https://www.sysnet.pe.kr/2/0/1682
따라서 해결 방법은 SecuritySafeCritical 특성을 적용하시면 됩니다.
[SecuritySafeCritical]
unsafe int FloatToIntBytes(float value)
{
int* pBytes = (int*)&value;
return *pBytes;
}
참고로, 2바이트 이상의 자료형을 바이트 배열로 반환하는
BitConverter 클래스도
GetBytes 메서드를 보면 SecuritySafeCritical 특성이 적용되었음을 볼 수 있습니다.
[SecuritySafeCritical, __DynamicallyInvokable]
public static unsafe byte[] GetBytes(int value)
{
byte[] buffer1 = new byte[4];
fixed (byte* numRef = buffer1)
{
*((int*) numRef) = value;
}
return buffer1;
}
(2021-04-09 업데이트)
경우에 따라 System.Security.VerificationException과 함께 TypeInitializationException 예외가 발생할 수도 있습니다. 예를 들어 해당 타입에 unsafe를 클래스 차원에서 정의한 경우,
unsafe class TestClass
{
private static int *_ptrData;
static TestClass()
{
_ptrData = ...;
}
}
static 생성자를 실행 시 VerificationException 예외가 발생한다면 자연스럽게 TypeInitializationException 예외로 이어지기 때문입니다. 이런 경우에는 SecuritySafeCritical 특성을 static 생성자에 부여해도 문제가 해결되지 않습니다. 대신 class 레벨로 설정해야 VerificationException 예외를 피할 수 있습니다.
[SecuritySafeCritical]
unsafe class TestClass
{
private static int *_ptrData;
static TestClass()
{
_ptrData = ...;
}
}
[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]