Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

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 = ...;
    }
}





[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 4/9/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 61  62  63  64  65  66  67  68  [69]  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
11905정성태5/21/201910540.NET Framework: 834. C# - 폴더 경로 문자열에서 "..", "." 표기를 고려한 최종 문자열을 얻는 방법 - 두 번째 이야기
11904정성태5/21/201916676.NET Framework: 833. C# - Open Hardware Monitor를 이용한 CPU 온도 정보 [1]파일 다운로드1
11903정성태5/21/201911710오류 유형: 540. .NET Core - System.PlatformNotSupportedException: The named version of this synchronization primitive is not supported on this platform.
11902정성태5/21/201910904오류 유형: 539. mstest 실행 시 "The directory name is invalid." 오류 발생
11901정성태5/21/201912024오류 유형: 538. msbuild 오류 - Could not find a part of the path '%LOCALAPPDATA%\Temp\2\.NETFramework,Version=v4.0.AssemblyAttributes.cs'
11900정성태5/18/201911320오류 유형: 537. "sfc /scannow" 실행 중 시스템이 부팅되는 현상
11899정성태5/17/201912297Linux: 9. Linux에서 윈도우의 OutputDebugString 대신 사용할 수 있는 syslog [1]
11898정성태5/16/201913641VC++: 130. C++ string의 c_str과 data 함수의 차이점 [3]
11897정성태5/16/201920228오류 유형: 536. Visual Studio - "Developer Pack"을 설치했는데도 "대상 프레임워크" 목록에 나오지 않는 경우 [2]
11896정성태5/15/201915012개발 환경 구성: 440. C#, C++ - double의 Infinity, NaN 표현 방식파일 다운로드1
11895정성태5/12/201913409.NET Framework: 832. ML.NET Model Builder - 회귀(Regression), 다중 분류(Multi-class classification) 예제파일 다운로드1
11894정성태5/10/201914559VS.NET IDE: 135. Visual Studio - ML.NET Model Builder 소개 [5]
11893정성태5/10/201912281오류 유형: 535. C# 6.0 이상의 문법을 컴파일 시 오류가 발생한다면?
11892정성태5/10/201912342웹: 38. HTTP Cookie의 expires 시간 형식(RFC7231)
11891정성태5/9/201914839.NET Framework: 831. (번역글) .NET Internals Cookbook Part 12 - Memory structure, attributes, handles
11890정성태5/8/201910553개발 환경 구성: 439. "Visual Studio Enterprise is required to execute the test." 메시지와 관련된 코드 기록
11889정성태5/8/201911319개발 환경 구성: 438. mstest, QTAgent의 로그 파일 설정 방법
11888정성태5/8/201926462.NET Framework: 830. C# - 비동기 호출을 취소하는 CancellationToken의 간단한 예제 코드 [1]파일 다운로드1
11887정성태5/8/201913119.NET Framework: 829. C# - yield 문을 사용할 수 있는 메서드의 조건
11886정성태5/7/201912164오류 유형: 534. mstest.exe 실행 시 "Visual Studio Enterprise is required to execute the test." 오류 [2]
11885정성태5/7/20199156오류 유형: 533. mstest.exe 실행 시 "File extension specified '.loadtest' is not a valid test extension." 오류 발생
11884정성태5/5/201912849.NET Framework: 828. C# DLL에서 Win32 C/C++처럼 dllexport 함수를 제공하는 방법 - 두 번째 이야기
11883정성태5/3/201917082.NET Framework: 827. C# - 인터넷 시간 서버로부터 받은 시간을 윈도우에 적용하는 방법파일 다운로드1
11882정성태5/2/201914042.NET Framework: 826. (번역글) .NET Internals Cookbook Part 11 - Various C# riddles파일 다운로드1
11881정성태4/28/201914322오류 유형: 532. .NET Core 프로젝트로 마이그레이션 시 "CS0579 Duplicate 'System.Reflection.AssemblyCompanyAttribute' attribute" 오류 발생
11880정성태4/25/201911087오류 유형: 531. 이벤트 로그 오류 - Task Scheduling Error: m->NextScheduledSPRetry 1547, m->NextScheduledEvent 1547
... 61  62  63  64  65  66  67  68  [69]  70  71  72  73  74  75  ...