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

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  8  9  10  11  [12]  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13341정성태5/8/20234199닷넷: 2114. C# 12 - 모든 형식의 별칭(Using aliases for any type)
13340정성태5/8/20234288오류 유형: 857. Microsoft.Data.SqlClient.SqlException - 0x80131904
13339정성태5/6/20235121닷넷: 2113. C# 12 - 기본 생성자(Primary Constructors)
13338정성태5/6/20234493닷넷: 2112. C# 12 - 기본 람다 매개 변수파일 다운로드1
13337정성태5/5/20234984Linux: 59. dockerfile - docker exec로 container에 접속 시 자동으로 실행되는 코드 적용
13336정성태5/4/20234813.NET Framework: 2111. C# - 바이너리 출력 디렉터리와 연관된 csproj 설정
13335정성태4/30/20234840.NET Framework: 2110. C# - FFmpeg.AutoGen 라이브러리를 이용한 기본 프로젝트 구성 - Windows Forms파일 다운로드1
13334정성태4/29/20234473Windows: 250. Win32 C/C++ - Modal 메시지 루프 내에서 SetWindowsHookEx를 이용한 Thread 메시지 처리 방법
13333정성태4/28/20233926Windows: 249. Win32 C/C++ - 대화창 템플릿을 런타임에 코딩해서 사용파일 다운로드1
13332정성태4/27/20233994Windows: 248. Win32 C/C++ - 대화창을 위한 메시지 루프 사용자 정의파일 다운로드1
13331정성태4/27/20233995오류 유형: 856. dockerfile - 구 버전의 .NET Core 이미지 사용 시 apt update 오류
13330정성태4/26/20233657Windows: 247. Win32 C/C++ - CS_GLOBALCLASS 설명
13329정성태4/24/20233906Windows: 246. Win32 C/C++ - 직접 띄운 대화창 템플릿을 위한 Modal 메시지 루프 생성파일 다운로드1
13328정성태4/19/20233537VS.NET IDE: 184. Visual Studio - Fine Code Coverage에서 동작하지 않는 Fake/Shim 테스트
13327정성태4/19/20233951VS.NET IDE: 183. C# - .NET Core/5+ 환경에서 Fakes를 이용한 단위 테스트 방법
13326정성태4/18/20235444.NET Framework: 2109. C# - 닷넷 응용 프로그램에서 SQLite 사용 (System.Data.SQLite) [1]파일 다운로드1
13325정성태4/18/20234685스크립트: 48. 파이썬 - PostgreSQL의 with 문을 사용한 경우 연결 개체 누수
13324정성태4/17/20234501.NET Framework: 2108. C# - Octave의 "save -binary ..."로 생성한 바이너리 파일 분석파일 다운로드1
13323정성태4/16/20234447개발 환경 구성: 677. Octave에서 Excel read/write를 위한 io 패키지 설치
13322정성태4/15/20235265VS.NET IDE: 182. Visual Studio - 32비트로만 빌드된 ActiveX와 작업해야 한다면?
13321정성태4/14/20234060개발 환경 구성: 676. WSL/Linux Octave - Python 스크립트 연동
13320정성태4/13/20233957개발 환경 구성: 675. Windows Octave 8.1.0 - Python 스크립트 연동
13319정성태4/12/20234464개발 환경 구성: 674. WSL 2 환경에서 GNU Octave 설치
13318정성태4/11/20234345개발 환경 구성: 673. JetBrains IDE에서 "Squash Commits..." 메뉴가 비활성화된 경우
13317정성태4/11/20234389오류 유형: 855. WSL 2 Ubuntu 20.04 - error: cannot communicate with server: Post http://localhost/v2/snaps/...
13316정성태4/10/20233645오류 유형: 854. docker-compose 시 "json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)" 오류 발생
1  2  3  4  5  6  7  8  9  10  11  [12]  13  14  15  ...