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

[Out] 형식의 int * 인자를 가진 함수에 대한 P/Invoke 호출 방법

다음과 같은 질문이 있군요. ^^

C# 에서 C++ DLL임포트 질문입니다.
; https://www.sysnet.pe.kr/3/0/4800

질문을 정리해 보면, C++ DLL에서 제공하는 함수가 다음과 같이 int * 형식의 인자를 가지고 있을 때,

__declspec(dllexport) void TestFunc(int *value1);

이 함수를 DllImport를 이용해 다음과 같이 P/Invoke 호출을 할 수 있느냐... 하는 것입니다.

[DllImport("Win32Project1.dll")]
internal static extern int TestFunc(IntPtr pValue);

일단, 저렇게 하는 것이 맞습니다. 하지만, TestFunc에 넘겨주는 IntPtr에 대한 처리를 잘 해야 합니다. 가령 다음과 같이 넘겨주면 어떻게 될까요?

IntPtr pValue = new IntPtr();
TestFunc(pValue);

운이 나쁘다면 이런 경우 다음과 같은 예외를 만날 수 있습니다.

Exception thrown: write access violation.

value1 was nullptr.

If there is a handler for this exception, the program may be safely continued.

왜냐하면, C++ DLL 측에서 대개는 입력 인자가 int 타입 등에 대한 포인터인 경우 다음과 같이 코딩했을 확률이 높기 때문입니다.

__declspec(dllexport) void TestFunc(int *value1)
{
    *value1 = 5; // C#에서 넘겨준 IntPtr은 기본값으로 0을 담고 있기 때문에,
                 // 이는 null ptr을 의미하므로 NULL 참조 예외 발생
}

또는 C++ 개발자가 이런 식으로 만들었을 수도 있습니다.

__declspec(dllexport) void TestFunc(int *value1)
{
    if (value1 != nullptr) // 호출 측에서 명시적으로 필요하다고 한 경우에만 값을 담도록 처리
    {
        *value1 = 5;
    }
}

위와 같은 경우라면 C# 호출 측에서는 예외가 발생하지 않지만 IntPtr에는 아무런 값도 없게 됩니다. 물론, 해당 [Out] 인자 값이 필요하지 않다면 별문제 없겠지만 필요한 경우라면 결국 값을 반환받지 못했으므로 원치 않는 결과가 나온 것입니다.




해결 방법은 간단합니다. 결국, IntPtr로 하여금 값을 담을 수 있는 주소에 대한 포인터가 되도록 만들어 주면 되는 것입니다.

방법은 여러 가지가 있는데요, 가장 간단하게는 C#에서도 직접 포인터를 써 주면 됩니다. 이렇게!

[DllImport("Win32Project1.dll")]
internal unsafe static extern int TestFunc(int *pValue);

private unsafe static void CallTestFunc2()
{
    int intValue;
    TestFunc(&intValue);
    Console.WriteLine("TestFunc2: " + intValue);
}

unsafe 예약어가 싫다면 이렇게도 가능합니다.

[DllImport("Win32Project1.dll")]
internal static extern int TestFunc(IntPtr pValue);

private static void CallTestFunc3()
{
    IntPtr pValue = Marshal.AllocHGlobal(4); // 4바이트 할당
    TestFunc(pValue);

    Console.WriteLine("CallTestFunc3: " + Marshal.ReadInt32(pValue));

    Marshal.FreeHGlobal(pValue);
}

약간 복잡하게 한다면 어쨌든 포인터 접근이 가능합니다.

private unsafe static void CallTestFunc3()
{
    IntPtr pValue = Marshal.AllocHGlobal(4); // 4바이트 할당
    TestFunc(pValue);

    int handle = *(int *)pValue.ToPointer();
    Console.WriteLine("CallTestFunc3: " + handle);

    Marshal.FreeHGlobal(pValue);
}

물론, Marshal.AllocHGlobal을 이용해 할당하는 대신 int 타입의 인스턴스를 가져다 써도 됩니다.

private unsafe static void CallTestFunc4()
{
    int intValue;
    int* pIntValue = &intValue;

    IntPtr pValue = new IntPtr(pIntValue);
    TestFunc(pValue);

    Console.WriteLine("CallTestFunc4: " + intValue);
}

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 2/5/2017]

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)
11897정성태5/16/201920005오류 유형: 536. Visual Studio - "Developer Pack"을 설치했는데도 "대상 프레임워크" 목록에 나오지 않는 경우 [2]
11896정성태5/15/201914804개발 환경 구성: 440. C#, C++ - double의 Infinity, NaN 표현 방식파일 다운로드1
11895정성태5/12/201913245.NET Framework: 832. ML.NET Model Builder - 회귀(Regression), 다중 분류(Multi-class classification) 예제파일 다운로드1
11894정성태5/10/201914414VS.NET IDE: 135. Visual Studio - ML.NET Model Builder 소개 [5]
11893정성태5/10/201912123오류 유형: 535. C# 6.0 이상의 문법을 컴파일 시 오류가 발생한다면?
11892정성태5/10/201912159웹: 38. HTTP Cookie의 expires 시간 형식(RFC7231)
11891정성태5/9/201914662.NET Framework: 831. (번역글) .NET Internals Cookbook Part 12 - Memory structure, attributes, handles
11890정성태5/8/201910404개발 환경 구성: 439. "Visual Studio Enterprise is required to execute the test." 메시지와 관련된 코드 기록
11889정성태5/8/201911121개발 환경 구성: 438. mstest, QTAgent의 로그 파일 설정 방법
11888정성태5/8/201926254.NET Framework: 830. C# - 비동기 호출을 취소하는 CancellationToken의 간단한 예제 코드 [1]파일 다운로드1
11887정성태5/8/201912936.NET Framework: 829. C# - yield 문을 사용할 수 있는 메서드의 조건
11886정성태5/7/201911976오류 유형: 534. mstest.exe 실행 시 "Visual Studio Enterprise is required to execute the test." 오류 [2]
11885정성태5/7/20199008오류 유형: 533. mstest.exe 실행 시 "File extension specified '.loadtest' is not a valid test extension." 오류 발생
11884정성태5/5/201912649.NET Framework: 828. C# DLL에서 Win32 C/C++처럼 dllexport 함수를 제공하는 방법 - 두 번째 이야기
11883정성태5/3/201916852.NET Framework: 827. C# - 인터넷 시간 서버로부터 받은 시간을 윈도우에 적용하는 방법파일 다운로드1
11882정성태5/2/201913838.NET Framework: 826. (번역글) .NET Internals Cookbook Part 11 - Various C# riddles파일 다운로드1
11881정성태4/28/201914112오류 유형: 532. .NET Core 프로젝트로 마이그레이션 시 "CS0579 Duplicate 'System.Reflection.AssemblyCompanyAttribute' attribute" 오류 발생
11880정성태4/25/201910919오류 유형: 531. 이벤트 로그 오류 - Task Scheduling Error: m->NextScheduledSPRetry 1547, m->NextScheduledEvent 1547
11879정성태4/24/201916069.NET Framework: 825. (번역글) .NET Internals Cookbook Part 10 - Threads, Tasks, asynchronous code and others파일 다운로드2
11878정성태4/22/201914105.NET Framework: 824. (번역글) .NET Internals Cookbook Part 9 - Finalizers, queues, card tables and other GC stuff파일 다운로드1
11877정성태4/22/201913992.NET Framework: 823. (번역글) .NET Internals Cookbook Part 8 - C# gotchas파일 다운로드1
11876정성태4/21/201913824.NET Framework: 822. (번역글) .NET Internals Cookbook Part 7 - Word tearing, locking and others파일 다운로드1
11875정성태4/21/201914173오류 유형: 530. Visual Studo에서 .NET Core 프로젝트를 열 때 "One or more errors occurred." 오류 발생
11874정성태4/20/201914201.NET Framework: 821. (번역글) .NET Internals Cookbook Part 6 - Object internals파일 다운로드1
11873정성태4/19/201913157.NET Framework: 820. (번역글) .NET Internals Cookbook Part 5 - Methods, parameters, modifiers파일 다운로드1
11872정성태4/17/201913644.NET Framework: 819. (번역글) .NET Internals Cookbook Part 4 - Type members파일 다운로드1
... 61  62  63  64  65  66  67  68  [69]  70  71  72  73  74  75  ...