Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)
(시리즈 글이 16개 있습니다.)
.NET Framework: 112. How to Interop DISPPARAMS
; https://www.sysnet.pe.kr/2/0/617

.NET Framework: 137. C#에서 Union 구조체 다루기
; https://www.sysnet.pe.kr/2/0/728

.NET Framework: 141. Win32 Interop - 크기가 정해지지 않은 배열을 C++에서 C#으로 전달하는 경우
; https://www.sysnet.pe.kr/2/0/737

.NET Framework: 168. [in,out] 배열을 C#에서 C/C++로 넘기는 방법
; https://www.sysnet.pe.kr/2/0/810

.NET Framework: 169. [in, out] 배열을 C#에서 C/C++로 넘기는 방법 - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/811

.NET Framework: 183. 구조체 포인터 인자에 대한 P/Invoke 정의
; https://www.sysnet.pe.kr/2/0/912

.NET Framework: 472. C/C++과 C# 사이의 메모리 할당/해제 방법
; https://www.sysnet.pe.kr/2/0/1784

.NET Framework: 620. C#에서 C/C++ 함수로 콜백 함수를 전달하는 예제 코드
; https://www.sysnet.pe.kr/2/0/11099

.NET Framework: 627. C++로 만든 DLL을 C#에서 사용하기
; https://www.sysnet.pe.kr/2/0/11111

.NET Framework: 686. C# - string 배열을 담은 구조체를 직렬화하는 방법
; https://www.sysnet.pe.kr/2/0/11319

.NET Framework: 757. 포인터 형 매개 변수를 갖는 C++ DLL의 함수를 C#에서 호출하는 방법
; https://www.sysnet.pe.kr/2/0/11533

.NET Framework: 978. C# - GUID 타입 전용의 UnmanagedType.LPStruct
; https://www.sysnet.pe.kr/2/0/12444

C/C++: 158. Visual C++ - IDL 구문 중 "unsigned long"을 인식하지 못하는 #import
; https://www.sysnet.pe.kr/2/0/13128

.NET Framework: 2058. [in,out] 배열을 C#에서 C/C++로 넘기는 방법 - 세 번째 이야기
; https://www.sysnet.pe.kr/2/0/13141

.NET Framework: 2083. C# - C++과의 연동을 위한 구조체의 fixed 배열 필드 사용 (2)
; https://www.sysnet.pe.kr/2/0/13205

닷넷: 2152. Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제
; https://www.sysnet.pe.kr/2/0/13429




Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제

아래와 같은 질문이 있는데요,

C++의 double pointer를 C#에서 구현하는 방법이 잘 안됩니다.
; https://www.sysnet.pe.kr/3/0/5922

이런 경우, C#이 제대로 동작하고 있는지 확신이 없다면 간단한 C/C++ DLL 예제를 만들어 검증하는 단계를 거치면 됩니다.

코드도 매우 간단한데요, C/C++ 측은 다음과 같은 코드를 만들어 두고,

#include "stdafx.h"
#include "InteropWin32.h"

DWORD* g_pItem = nullptr;

INTEROPWIN32_API void fnInterop(DWORD** ppItem)
{
    if (g_pItem == nullptr)
    {
        g_pItem = new DWORD[10];

        for (int i = 0; i < 10; i++)
        {
            g_pItem[i] = i;
        }
    }

    *ppItem = g_pItem;
}

C# 측에서는 저 함수를 호출하는 코드를 이런 식으로 만들 수 있습니다.

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

namespace InteropTest
{
    class Program
    {
        // x86 대상인 경우, 기본 Win32 API의 호출 규약이 Cdecl이므로,
        // [DllImport("InteropWin32.dll", CallingConvention = CallingConvention.Cdecl)]

        // x64 대상인 경우, CallingConvention 필요 없음
        [DllImport("InteropWin32.dll")]
        public static extern void fnInterop(ref IntPtr data);

        static void Main(string[] args)
        {
            IntPtr ptr = IntPtr.Zero;
            fnInterop1(ref ptr);

            int[] elems = new int[10];

            Marshal.Copy(ptr, elems, 0, 10);

            foreach (int elem in elems)
            {
                Console.Write($"{elem},"); // 출력 결과: 0,1,2,3,4,5,6,7,8,9,
            }
        }
    }
}

쉽죠?!!! ^^ 만약 "ref IntPtr"이 못 미덥다면 포인터 연산을 직접 하는 것도 가능합니다.

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

namespace InteropTest
{
    unsafe class Program
    {
        [DllImport("InteropWin32.dll")]
        public static extern void fnInterop(int **ppItem);

        static void Main(string[] args)
        {
            int* p = null;
            fnInterop2(&p);

            for (int i = 0; i < 10; i ++)
            {
                Console.Write($"{p[i]},"); // 출력 결과: 0,1,2,3,4,5,6,7,8,9,
            }
        }
    }
}

이렇게 검증이 되었으니, 이제 질문자의 상황에서는 다른 요인으로 인한 문제가 있음을 예상할 수 있습니다.

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




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 11/6/2023]

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)
11785정성태11/21/201813482디버깅 기술: 120. windbg 분석 사례 - ODP.NET 사용 시 Finalizer에서 System.AccessViolationException 예외 발생으로 인한 비정상 종료
11784정성태11/18/201813132Graphics: 32. .NET으로 구현하는 OpenGL (7), (8) - Matrices and Uniform Variables, Model, View & Projection Matrices파일 다운로드1
11783정성태11/18/201811227오류 유형: 504. 윈도우 환경에서 docker가 설치된 컴퓨터 간의 ping IP 주소 풀이 오류
11782정성태11/18/201811008Windows: 152. 윈도우 10에서 사라진 "Adapters and Bindings" 네트워크 우선순위 조정 기능 - 두 번째 이야기
11781정성태11/17/201813213개발 환경 구성: 422. SFML.NET 라이브러리 설정 방법 [1]파일 다운로드1
11780정성태11/17/201814673오류 유형: 503. vcpkg install bzip2 빌드 에러 - "Error: Building package bzip2:x86-windows failed with: BUILD_FAILED"
11779정성태11/17/201815046개발 환경 구성: 421. vcpkg 업데이트 [1]
11778정성태11/14/201812816.NET Framework: 803. UWP 앱에서 한 컴퓨터(localhost, 127.0.0.1) 내에서의 소켓 연결
11777정성태11/13/201811890오류 유형: 502. Your project does not reference "..." framework. Add a reference to "..." in the "TargetFrameworks" property of your project file and then re-run NuGet restore.
11776정성태11/13/201811144.NET Framework: 802. Windows에 로그인한 계정이 마이크로소프트의 계정인지, 로컬 계정인지 알아내는 방법
11775정성태11/13/201813682Graphics: 31. .NET으로 구현하는 OpenGL (6) - Texturing파일 다운로드1
11774정성태11/8/201811541Graphics: 30. .NET으로 구현하는 OpenGL (4), (5) - Shader파일 다운로드1
11773정성태11/7/201811270Graphics: 29. .NET으로 구현하는 OpenGL (3) - Index Buffer파일 다운로드1
11772정성태11/6/201813549Graphics: 28. .NET으로 구현하는 OpenGL (2) - VAO, VBO파일 다운로드1
11771정성태11/5/201812781사물인터넷: 56. Audio Jack 커넥터의 IR 적외선 송신기 - 두 번째 이야기 [1]
11770정성태11/5/201819739Graphics: 27. .NET으로 구현하는 OpenGL (1) - OpenGL.Net 라이브러리 [3]파일 다운로드1
11769정성태11/5/201811568오류 유형: 501. 프로젝트 msbuild Publish 후 connectionStrings의 문자열이 $(ReplacableToken_...)로 바뀌는 문제
11768정성태11/2/201811497.NET Framework: 801. SOIL(Simple OpenGL Image Library) - Native DLL 및 .NET DLL 제공
11767정성태11/1/201813036사물인터넷: 55. New NodeMcu v3(ESP8266)의 IR LED (적외선 송신) 제어파일 다운로드1
11766정성태10/31/201814364사물인터넷: 54. 아두이노 환경에서의 JSON 파서(ArduinoJson) 사용법
11765정성태10/26/201812002개발 환경 구성: 420. Visual Studio Code - Arduino Board Manager를 이용한 사용자 정의 보드 선택
11764정성태10/26/201815565개발 환경 구성: 419. MIT 라이선스로 무료 공개된 Detours API 후킹 라이브러리 [2]
11763정성태10/25/201813507사물인터넷: 53. New NodeMcu v3(ESP8266)의 https 통신
11762정성태10/25/201814318사물인터넷: 52. New NodeMCU v3(ESP8266)의 http 통신파일 다운로드1
11761정성태10/25/201813992Graphics: 26. 임의 축을 기반으로 3D 벡터 회전파일 다운로드1
11760정성태10/24/201810484개발 환경 구성: 418. Azure - Runbook 내에서 또 다른 Runbook 스크립트를 실행
... 61  62  63  64  65  66  67  68  69  70  71  72  73  [74]  75  ...