성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] Java - How to use the Foreign Funct...
[정성태] 제가 큰 실수를 했군요. ^^; Delegate를 통한 Bein...
[정성태] Working with Rust Libraries from C#...
[정성태] Detecting blocking calls using asyn...
[정성태] 아쉽게도, 커뮤니티는 아니고 개인 블로그입니다. ^^
[정성태] 질문이 잘 이해가 안 됩니다. 우선, 해당 소스코드에서 ILis...
[양승조
] var대신 dinamic으로 선언해서 해결은 했습니다. 맞는 해...
[양승조
] 또 막혔습니다. ㅠㅠ var list = props[i].Ge...
[양승조
] 아. 감사합니다. 어제는 안됐던것 같은데....정신을 차려야겠네...
[정성태] "props[i].GetValue(props[i])" 코드에서 ...
글쓰기
제목
이름
암호
전자우편
HTML
홈페이지
유형
제니퍼 .NET
닷넷
COM 개체 관련
스크립트
VC++
VS.NET IDE
Windows
Team Foundation Server
디버깅 기술
오류 유형
개발 환경 구성
웹
기타
Linux
Java
DDK
Math
Phone
Graphics
사물인터넷
부모글 보이기/감추기
내용
<div style='display: inline'> <h1 style='font-family: Malgun Gothic, Consolas; font-size: 20pt; color: #006699; text-align: center; font-weight: bold'>C# COM 개체를 PIA(Primary Interop Assembly)로써 "Embed Interop Types" 참조하는 방법</h1> <p> 인터페이스의 경우 다른 프로젝트에서 참조할 때 "Embed Interop Types"를 이용하면 DLL 의존성 없이 인터페이스 정의만 가져오는 것이 허용됩니다. 보통 Office 계열의 COM 개체를 다룰 때 사용하지만 C# 프로젝트에서도 이를 사용하는 것이 가능한데요.<br /> <br /> 간단하게 예를 들어 볼까요?<br /> <br /> 우선, 인터페이스 정의만 담은 DLL을 하나 생성하고,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > // ClassLibrary1 프로젝트 using System; using System.Runtime.InteropServices; namespace ClassLibrary1 { [ComVisible(true)] [Guid("62A4A0A9-8791-444B-ABF7-8BFD23DFF0FB")] [InterfaceType(ComInterfaceType.InterfaceIsDual)] public interface IAdminCode { void SetRegistryValue(); } } </pre> <br /> 이것을 상속받아 구현한 C# COM 개체를 다음과 같이 별도의 프로젝트에 만들었을 때,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > // ClassLibrary2 프로젝트 using ClassLibrary1; using System; using System.Runtime.InteropServices; using System.Windows.Forms; namespace ClassLibrary2 { [ComVisible(true)] [Guid("296A7E30-8592-4EE5-8FE1-E9DAF86D146E")] [ClassInterface(ClassInterfaceType.AutoDual)] public class Class1 : <span style='color: blue; font-weight: bold'>IAdminCode</span> { public void SetRegistryValue() { MessageBox.Show("TEST"); } } } </pre> <br /> 일반적으로는 IAdminCode 인터페이스를 담고 있는 ClassLibrary1.dll도 함께 배포를 해야만 정상적인 동작을 합니다. 하지만, PIA(Primary Interop Assembly)를 이용하면 ClassLibrary1.dll에 대한 의존성을 끊을 수 있습니다. 이를 위해, ClassLibrary2에서 ClassLibrary1을 "Embed Interop Types" == "True"로 두면 되는데,<br /> <br /> [<a target='tab' href='https://www.sysnet.pe.kr/2/0/1624'>ASP.NET에서 Server.CreateObject와 COM Interop 클래스 생성의 차이점</a>]<br /> <img alt='server_create_object_1.png' src='/SysWebRes/bbs/server_create_object_1.png' /><br /> <br /> 현재 단계에서는 저렇게 설정하면 다음과 같은 CS1759 오류가 발생합니다.<br /> <br /> <div style='BACKGROUND-COLOR: #ccffcc; padding: 10px 10px 5px 10px; MARGIN: 0px 10px 10px 10px; FONT-FAMILY: Malgun Gothic, Consolas, Verdana; COLOR: #005555'> Cannot embed interop types from assembly 'ClassLibrary1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because it is missing either the 'System.Runtime.InteropServices.ImportedFromTypeLibAttribute' attribute or the 'System.Runtime.InteropServices.PrimaryInteropAssemblyAttribute' attribute.<br /> </div><br /> <br /> 왜냐하면, 우리가 만든 ClassLibrary1.dll은 "Primary Interop Assembly"가 아니기 때문입니다. 당연히 저 오류를 없애려면 DLL을 PIA로 만들어야 하는데, 그 방법은 오류 메시지에도 나오듯이 PIA 특성을 해당 DLL에 부여하면 됩니다. 따라서, ClassLibrary1.dll 프로젝트의 AssemblyInfo.cs에 다음과 같이 PIA 특성을 추가합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > [assembly: PrimaryInteropAssemblyAttribute(1, 0)] </pre> <br /> 하지만, 일단 저렇게 해서 ClassLibrary1.dll을 PIA로 인식시킬 수는 있지만 이번에는 CS1756 오류 메시지가 발생합니다.<br /> <br /> <div style='BACKGROUND-COLOR: #ccffcc; padding: 10px 10px 5px 10px; MARGIN: 0px 10px 10px 10px; FONT-FAMILY: Malgun Gothic, Consolas, Verdana; COLOR: #005555'> CS1756 Interop type 'IAdminCode' cannot be embedded because it is missing the required 'System.Runtime.InteropServices.ComImportAttribute' attribute.<br /> </div><br /> <br /> 메시지에 나오는 것처럼, 의존성 없는 Import를 원하는 인터페이스에 대해 ComImport 특성을 부여해야 합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > using System; using System.Runtime.InteropServices; namespace ClassLibrary1 { [ComVisible(true)] [Guid("23172f2f-a3d3-4180-97ae-7805f74a5a46")] [InterfaceType(ComInterfaceType.InterfaceIsDual)] <span style='color: blue; font-weight: bold'>[ComImportAttribute()]</span> public interface IAdminCode { void SetRegistryValue(); } } </pre> <br /> 여기까지 해서 빌드하면 정상적으로 PIA와 그것을 참조하는 측에서 "Embed Interop Types" 옵션을 사용해 DLL 의존성을 끊을 수 있습니다.<br /> <br /> <hr style='width: 50%' /><br /> <br /> 이에 더해 ConsoleApp1.exe 프로젝트를 만들어, 마찬가지로 ClassLibrary1.dll에 대해 "Embed Interop Types" 참조를 하고 다음과 같이 ClassLibrary2.dll에서 제공하는 C# COM 개체를 아무런 의존성 없이 사용할 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > using ClassLibrary1; using System; namespace ConsoleApp1 { class Program { static void Main(string[] args) { <span style='color: blue; font-weight: bold'>Guid guid = new Guid("{296A7E30-8592-4EE5-8FE1-E9DAF86D146E}");</span> Type type = Type.GetTypeFromCLSID(guid); <span style='color: blue; font-weight: bold'>object comObject = Activator.CreateInstance(type);</span> <span style='color: blue; font-weight: bold'>IAdminCode ac = comObject as IAdminCode;</span> ac.SetRegistryValue(); } } } </pre> <br /> IAdminCode 사용을 위해 ClassLibrary1.dll을 참조하지만 "Embed Interop Types" 옵션을 켰으므로 응용 프로그램 배포 시에는 ConsoleApp1.exe 파일과 해당 C# COM 개체를 포함한 ClassLibrary2.dll만을 배포해 동작시키는 것이 가능합니다.<br /> <br /> <hr style='width: 50%' /><br /> <br /> 참고로, 위의 예제에서는 인터페이스와 구현을 각각 ClassLibrary1, ClassLibrary2 프로젝트에 분리했는데요. 그냥 하나로 합쳐도 무방합니다. 즉, IAdminCode 인터페이스를 ClassLibrary2 프로젝트에 추가한 다음 ConsoleApp1에서는 ClassLibrary2 프로젝트를 PIA 참조해도 상관없습니다.<br /> <br /> <a target='tab' href='https://www.sysnet.pe.kr/bbs/DownloadAttachment.aspx?fid=1790&boardid=331301885'>첨부 파일은 2개의 프로젝트를 포함</a>하는데, 각각 "ClassLibrary1, ClassLibrary2, ConsoleApp1"로 나뉜 것과 "ClassLibrary2, ConsoleApp1"로 나뉜 것을 포함합니다.<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
1951
(왼쪽의 숫자를 입력해야 합니다.)