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)
13491정성태12/19/20232272Linux: 63. 리눅스 - 다중 그룹 또는 사용자를 리소스에 권한 부여
13490정성태12/19/20232403개발 환경 구성: 698. Golang - GLIBC 의존을 없애는 정적 빌드 방법
13489정성태12/19/20232178개발 환경 구성: 697. GoLand에서 ldflags 지정 방법
13488정성태12/18/20232115오류 유형: 884. HTTP 500.0 - 명령행에서 실행한 ASP.NET Core 응용 프로그램을 실행하는 방법
13487정성태12/16/20232417개발 환경 구성: 696. C# - 리눅스용 AOT 빌드를 docker에서 수행 [1]
13486정성태12/15/20232234개발 환경 구성: 695. Nuget config 파일에 값 설정/삭제 방법
13485정성태12/15/20232125오류 유형: 883. dotnet build/restore - error : Root element is missing
13484정성태12/14/20232203개발 환경 구성: 694. Windows 디렉터리 경로를 WSL의 /mnt 포맷으로 구하는 방법
13483정성태12/14/20232348닷넷: 2184. C# - 하나의 resource 파일을 여러 프로그램에서 (AOT 시에도) 사용하는 방법파일 다운로드1
13482정성태12/13/20233030닷넷: 2183. C# - eFriend Expert OCX 예제를 .NET Core/5+ Console App에서 사용하는 방법 [2]파일 다운로드1
13481정성태12/13/20232331개발 환경 구성: 693. msbuild - .NET Core/5+ 프로젝트에서 resgen을 이용한 리소스 파일 생성 방법파일 다운로드1
13480정성태12/12/20232729개발 환경 구성: 692. Windows WSL 2 + Chrome 웹 브라우저 설치
13479정성태12/11/20232387개발 환경 구성: 691. WSL 2 (Ubuntu) + nginx 환경 설정
13477정성태12/8/20232640닷넷: 2182. C# - .NET 7부터 추가된 Int128, UInt128 [1]파일 다운로드1
13476정성태12/8/20232329닷넷: 2181. C# - .NET 8 JsonStringEnumConverter의 AOT를 위한 개선파일 다운로드1
13475정성태12/7/20232421닷넷: 2180. .NET 8 - 함수 포인터에 대한 Reflection 정보 조회파일 다운로드1
13474정성태12/6/20232236개발 환경 구성: 690. 닷넷 코어/5+ 버전의 ilasm/ildasm 실행 파일 구하는 방법 - 두 번째 이야기
13473정성태12/5/20232516닷넷: 2179. C# - 값 형식(Blittable)을 메모리 복사를 이용해 바이트 배열로 직렬화/역직렬화파일 다운로드1
13472정성태12/4/20232251C/C++: 164. Visual C++ - InterlockedCompareExchange128 사용 방법
13471정성태12/4/20232364Copilot - To enable GitHub Copilot, authorize this extension using GitHub's device flow
13470정성태12/2/20232695닷넷: 2178. C# - .NET 8부터 COM Interop에 대한 자동 소스 코드 생성 도입파일 다운로드1
13469정성태12/1/20232463닷넷: 2177. C# - (Interop DLL 없이) CoClass를 이용한 COM 개체 생성 방법파일 다운로드1
13468정성태12/1/20232354닷넷: 2176. C# - .NET Core/5+부터 달라진 RCW(Runtime Callable Wrapper) 대응 방식파일 다운로드1
13467정성태11/30/20232459오류 유형: 882. C# - Unhandled exception. System.Runtime.InteropServices.COMException (0x800080A5)파일 다운로드1
13466정성태11/29/20232627닷넷: 2175. C# - DllImport 메서드의 AOT 지원을 위한 LibraryImport 옵션
13465정성태11/28/20232364개발 환경 구성: 689. MSBuild - CopyToOutputDirectory가 "dotnet publish" 시에는 적용되지 않는 문제파일 다운로드1
1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...