Microsoft MVP성태의 닷넷 이야기
.NET Framework: 3.1. Interface를 사용하면. [링크 복사], [링크+제목 복사],
조회: 18436
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
부모글 보이기/감추기


.NET Class를 Native 클라이언트에게 제공하는 목적으로는 Interface를 사용하도록 권장하고 있습니다.
그래야 vtable의 순서 등을 정확하게 유지하는 contract를 보장할 수 있기 때문인데요.

방법은 그리 어렵지 않습니다. 해당 클래스를 Interface로부터 상속받도록 하고, ClassInterfaceType.None을 지정해 주시면 됩니다.

다음은 그에 대한 코드입니다.

namespace ClassLibrary1
{

    [ComVisible(true)]
    [Guid("23172f2f-a3d3-4180-97ae-7805f74a5a46")]
    [InterfaceType(ComInterfaceType.InterfaceIsDual)]
    public interface ISecure
    {
        bool CheckLicense();
    }

    [ComVisible(true)]
    [Guid("23172f2f-a3d3-4180-97ae-7805f74a5a45")]
    [ClassInterface(ClassInterfaceType.None)]
    public class SecureWrap : ISecure
    {
        public bool CheckLicense()
        {
            MessageBox.Show("1111111111", "222222222222", MessageBoxButtons.OK);
            return true;
        }
    }
}

이에 대한 TLB 파일을 Visual C++에서 import 시키면 다음과 같이 간결한 구조의 TLH 파일이 생성됩니다.

#pragma once
#pragma pack(push, 8)

#include <comdef.h>

struct __declspec(uuid("23172f2e-a3d3-4180-97ae-7805f74a5a49"))
/* LIBID */ __ClassLibrary1;
struct __declspec(uuid("23172f2f-a3d3-4180-97ae-7805f74a5a46"))
/* dual interface */ ISecure;
struct /* coclass */ SecureWrap;

_COM_SMARTPTR_TYPEDEF(ISecure, __uuidof(ISecure));

struct __declspec(uuid("23172f2f-a3d3-4180-97ae-7805f74a5a46"))
ISecure : IDispatch
{
    VARIANT_BOOL CheckLicense ( );
    virtual HRESULT __stdcall raw_CheckLicense (
        /*[out,retval]*/ VARIANT_BOOL * pRetVal ) = 0;
};

struct __declspec(uuid("23172f2f-a3d3-4180-97ae-7805f74a5a45"))
SecureWrap;

#include "d:\temp2\consolecpp\debug\classlibrary1.tli"

#pragma pack(pop)

_TypePtr 등의 Smart Pointer 정의도 필요 없게 되었음을 확인할 수 있습니다.
이를 직접 사용하게 되는 Visual C++ 코드 역시 다음과 같이 간단하게 이뤄집니다.

#include "stdafx.h"
#import "..\ClassLibrary1\bin\Debug\ClassLibrary1.tlb" no_namespace

void _tmain(int argc, _TCHAR* argv[])
{
	CoInitialize( NULL );

	{	
		ISecurePtr ptr = ISecurePtr( __uuidof( SecureWrap ) );
		ptr->CheckLicense();
	}

	CoUninitialize();
}







[최초 등록일: ]
[최종 수정일: 3/20/2023]

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

비밀번호

댓글 작성자
 



2011-10-22 06시50분
CoInitialize 없이 C# COM 개체를 생성하는 경우, Visual Studio 출력 창에 다음과 같은 디버그 메시지가 나올 수 있습니다.

First-chance exception at 0x7561b9bc in [...].exe: Microsoft C++ exception: _com_error at memory location 0x002be9f4..
정성태

1  2  3  4  5  6  7  8  9  10  11  [12]  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13348정성태5/10/20234038.NET Framework: 2119. C# - Semantic Kernel의 "Basic Loading of the Kernel" 예제
13347정성태5/10/20234400.NET Framework: 2118. C# - Semantic Kernel의 Prompt chaining 예제파일 다운로드1
13346정성태5/10/20234247오류 유형: 858. RDP 원격 환경과 로컬 PC 간의 Ctrl+C, Ctrl+V 복사가 안 되는 문제
13345정성태5/9/20235696.NET Framework: 2117. C# - (OpenAI 기반의) Microsoft Semantic Kernel을 이용한 자연어 처리 [1]파일 다운로드1
13344정성태5/9/20236814.NET Framework: 2116. C# - OpenAI API 사용 - 지원 모델 목록 [1]파일 다운로드1
13343정성태5/9/20234701디버깅 기술: 192. Windbg - Hyper-V VM으로 이더넷 원격 디버깅 연결하는 방법
13342정성태5/8/20234566.NET Framework: 2115. System.Text.Json의 역직렬화 시 필드/속성 주의
13341정성태5/8/20234316닷넷: 2114. C# 12 - 모든 형식의 별칭(Using aliases for any type)
13340정성태5/8/20234445오류 유형: 857. Microsoft.Data.SqlClient.SqlException - 0x80131904
13339정성태5/6/20235232닷넷: 2113. C# 12 - 기본 생성자(Primary Constructors)
13338정성태5/6/20234614닷넷: 2112. C# 12 - 기본 람다 매개 변수파일 다운로드1
13337정성태5/5/20235095Linux: 59. dockerfile - docker exec로 container에 접속 시 자동으로 실행되는 코드 적용
13336정성태5/4/20234910.NET Framework: 2111. C# - 바이너리 출력 디렉터리와 연관된 csproj 설정
13335정성태4/30/20234966.NET Framework: 2110. C# - FFmpeg.AutoGen 라이브러리를 이용한 기본 프로젝트 구성 - Windows Forms파일 다운로드1
13334정성태4/29/20234573Windows: 250. Win32 C/C++ - Modal 메시지 루프 내에서 SetWindowsHookEx를 이용한 Thread 메시지 처리 방법
13333정성태4/28/20234068Windows: 249. Win32 C/C++ - 대화창 템플릿을 런타임에 코딩해서 사용파일 다운로드1
13332정성태4/27/20234113Windows: 248. Win32 C/C++ - 대화창을 위한 메시지 루프 사용자 정의파일 다운로드1
13331정성태4/27/20234073오류 유형: 856. dockerfile - 구 버전의 .NET Core 이미지 사용 시 apt update 오류
13330정성태4/26/20233766Windows: 247. Win32 C/C++ - CS_GLOBALCLASS 설명
13329정성태4/24/20234049Windows: 246. Win32 C/C++ - 직접 띄운 대화창 템플릿을 위한 Modal 메시지 루프 생성파일 다운로드1
13328정성태4/19/20233668VS.NET IDE: 184. Visual Studio - Fine Code Coverage에서 동작하지 않는 Fake/Shim 테스트
13327정성태4/19/20234043VS.NET IDE: 183. C# - .NET Core/5+ 환경에서 Fakes를 이용한 단위 테스트 방법
13326정성태4/18/20235562.NET Framework: 2109. C# - 닷넷 응용 프로그램에서 SQLite 사용 (System.Data.SQLite) [1]파일 다운로드1
13325정성태4/18/20234788스크립트: 48. 파이썬 - PostgreSQL의 with 문을 사용한 경우 연결 개체 누수
13324정성태4/17/20234604.NET Framework: 2108. C# - Octave의 "save -binary ..."로 생성한 바이너리 파일 분석파일 다운로드1
13323정성태4/16/20234569개발 환경 구성: 677. Octave에서 Excel read/write를 위한 io 패키지 설치
1  2  3  4  5  6  7  8  9  10  11  [12]  13  14  15  ...