Microsoft MVP성태의 닷넷 이야기
COM 개체 관련: 9. _bstr_t, CComBSTR, string 클래스 사용 [링크 복사], [링크+제목 복사],
조회: 22223
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

저는 _bstr_t, CComBSTR 클래스와 STL의 string 클래스를 주로 사용해서 "문자열 연산"을 합니다.

한번 보시겠어요! ^^

HTML 스크립트에서 다음처럼 메서드를 부른다고 할 때,
var szText = obj.DoWork( "TEST" );

다음과 같이 정의할 것입니다.
HRESULT DoWork( [in] BSTR szInText, [out,retval] BSTR *szOutText )
{
 _bstr_t bstrText = szInText;
 string strText = LPCSTR( bstrText );

 *szOutText = _bstr_t( strText.c_str() ).copy();
 return S_OK;
}

그런데, 이때 주의할 점이 몇 가지 있습니다.

1. _bstr_t::LPCSTR 연산자 사용 주의:
  만약, 해당 _bstr_t 클래스가 보유하고 있는 텍스트의 length가 0인 경우에는, 오류가 발생합니다.

2. _bstr_t 클래스는 대용량 문자열을 감당할 수 없습니다. 제가 정확한 수치는 테스트를 안 해봐서 잘 모르겠습니다. 아마도 _bstr_t 클래스에서 내부적으로 사용하는 _com_util::ConvertStringToBSTR 함수의 오류 같은데요.
MB 단위의 글자는 여지없이 다운되니 조심하셔야 됩니다. 그런 경우, _bstr_t 클래스는 사용하지 마시고, CComBSTR 클래스를 사용해야 됩니다. 대신에, CComBSTR 클래스 같은 경우는 LPCSTR() 연산자가 없으므로 ANSI 문자열로 변환할 경우에는 WideCharToMultiByte 함수를 사용해야 하는 불편함이 있습니다.

위의 2가지를 반영한 코드를 다시 보겠습니다.

HRESULT DoWork( [in] BSTR szInText, [out,retval] BSTR *szOutText )
{
 _bstr_t bstrText = szInText;
 if ( bstrText.length() == 0 ) return S_OK;

 string strText = LPCSTR( bstrText );

 // 만약 strText에 대용량 문자열이 저장된 경우
 CComBSTR suText = strText.c_str();
 *szOutText = suText.Copy();
 return S_OK;
}

최근에, VS.NET에서 COM 개체를 만들 일이 좀 있었는데요.
VC++ 6.0에서는 제가 그동안 모아놓은 라이브러리를 습관적으로 Include 시켜서 알지 못했는데, _bstr_t와 관련해서 시행착오를 겪었습니다.
물론, 이 점은 VC++ 6.0에서도 마찬가지입니다.

_bstr_t 클래스는 <comutil.h>에 정의되어 있습니다.
그런데 그 안에서 예외에 대한 처리를 _com_error에서 하는데, 그 때문에, _bstr_t, _variant_t 클래스 등을 사용하기 위해서는
#include <comutil.h>
#pragma comment(lib, "comsupp.lib")
위와 같이 해주어야 합니다.

아시는 분은 아시겠지만, 위의 구문은
#include <comdef.h>
하나로 해결이 되어지죠.









[최초 등록일: ]
[최종 수정일: 7/10/2021]

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

비밀번호

댓글 작성자
 



2022-07-18 09시35분
[ㅇㅇ] #include <comdef.h> 로 사용이 되네요. 감사합니다!
[guest]

... 61  62  63  64  65  66  67  68  [69]  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12211정성태4/27/202019292개발 환경 구성: 486. WSL에서 Makefile로 공개된 리눅스 환경의 C/C++ 소스 코드 빌드
12210정성태4/20/202020768.NET Framework: 903. .NET Framework의 Strong-named 어셈블리 바인딩 (1) - app.config을 이용한 바인딩 리디렉션 [1]파일 다운로드1
12209정성태4/13/202017450오류 유형: 614. 리눅스 환경에서 C/C++ 프로그램이 Segmentation fault 에러가 발생한 경우 (2)
12208정성태4/12/202016024Linux: 29. 리눅스 환경에서 C/C++ 프로그램이 Segmentation fault 에러가 발생한 경우
12207정성태4/2/202015899스크립트: 19. Windows PowerShell의 NonInteractive 모드
12206정성태4/2/202018494오류 유형: 613. 파일 잠금이 바로 안 풀린다면? - The process cannot access the file '...' because it is being used by another process.
12205정성태4/2/202015124스크립트: 18. Powershell에서는 cmd.exe의 명령어를 지원하진 않습니다.
12204정성태4/1/202015152스크립트: 17. Powershell 명령어에 ';' (semi-colon) 문자가 포함된 경우
12203정성태3/18/202018001오류 유형: 612. warning: 'C:\ProgramData/Git/config' has a dubious owner: '...'.
12202정성태3/18/202021233개발 환경 구성: 486. .NET Framework 프로젝트를 위한 GitLab CI/CD Runner 구성
12201정성태3/18/202018481오류 유형: 611. git-credential-manager.exe: Using credentials for username "Personal Access Token". [1]
12200정성태3/18/202018565VS.NET IDE: 145. NuGet + Github 라이브러리 디버깅 관련 옵션 3가지 - "Enable Just My Code" / "Enable Source Link support" / "Suppress JIT optimization on module load (Managed only)"
12199정성태3/17/202016210오류 유형: 610. C# - CodeDomProvider 사용 시 Unhandled Exception: System.IO.DirectoryNotFoundException: Could not find a part of the path '...\f2_6uod0.tmp'.
12198정성태3/17/202019582오류 유형: 609. SQL 서버 접속 시 "Cannot open user default database. Login failed."
12197정성태3/17/202018917VS.NET IDE: 144. .NET Core 콘솔 응용 프로그램을 배포(publish) 시 docker image 자동 생성 - 두 번째 이야기 [1]
12196정성태3/17/202016018오류 유형: 608. The ServicedComponent being invoked is not correctly configured (Use regsvcs to re-register).
12195정성태3/16/202018322.NET Framework: 902. C# - 프로세스의 모든 핸들을 열람 - 세 번째 이야기
12194정성태3/16/202021032오류 유형: 607. PostgreSQL - Npgsql.NpgsqlException: sorry, too many clients already
12193정성태3/16/202018006개발 환경 구성: 485. docker - SAP Adaptive Server Enterprise 컨테이너 실행 [1]
12192정성태3/14/202020038개발 환경 구성: 484. docker - Sybase Anywhere 16 컨테이너 실행
12191정성태3/14/202021092개발 환경 구성: 483. docker - OracleXE 컨테이너 실행 [1]
12190정성태3/14/202015700오류 유형: 606. Docker Desktop 업그레이드 시 "The process cannot access the file 'C:\Program Files\Docker\Docker\resources\dockerd.exe' because it is being used by another process."
12189정성태3/13/202021299개발 환경 구성: 482. Facebook OAuth 처리 시 상태 정보 전달 방법과 "유효한 OAuth 리디렉션 URI" 설정 규칙
12188정성태3/13/202026068Windows: 169. 부팅 시점에 실행되는 chkdsk 결과를 확인하는 방법
12187정성태3/12/202015678오류 유형: 605. NtpClient was unable to set a manual peer to use as a time source because of duplicate error on '...'.
12186정성태3/12/202017444오류 유형: 604. The SysVol Permissions for one or more GPOs on this domain controller and not in sync with the permissions for the GPOs on the Baseline domain controller.
... 61  62  63  64  65  66  67  68  [69]  70  71  72  73  74  75  ...