Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 3개 있습니다.)
(시리즈 글이 3개 있습니다.)
.NET Framework: 127. ClickOnce로 ActiveX를 같이 배포하는 방법
; https://www.sysnet.pe.kr/2/0/692

개발 환경 구성: 133. Registry 등록 과정 없이 COM 개체 사용 - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/1167

개발 환경 구성: 469. Reg-free COM 개체 사용을 위한 manifest 파일 생성 도구 - COMRegFreeManifest
; https://www.sysnet.pe.kr/2/0/12160




Reg-free COM 개체 사용을 위한 manifest 파일 생성 도구 - COMRegFreeManifest

COM 객체를 regsvr32.exe로 등록하지 않아도, manifest 파일을 통해 직접 생성해 사용할 수 있다고 설명했었습니다.

Registry 등록 없이 COM 개체 사용
; https://www.sysnet.pe.kr/2/1/262

일례로 다음의 글들이 모두 그런 식으로,

C# - VLC(ActiveX) 컨트롤을 레지스트리 등록없이 사용하는 방법
; https://www.sysnet.pe.kr/2/0/1640

eBEST XingAPI의 C# 래퍼 버전 - XingAPINet Nuget 패키지
; https://www.sysnet.pe.kr/2/0/12134

C# - 키움 Open API+ 사용 시 Registry 등록 없이 KHOpenAPI.ocx 사용하는 방법
; https://www.sysnet.pe.kr/2/0/12129

COM 객체를 등록하지 않고 같은 폴더에 있는 dll로부터 로드하고 있습니다. 그런데... 가끔 해보는 거지만 그때마다 manifest 파일을 일일이 만들려니 꽤나... ^^; 귀찮습니다. 그래서 어차피, tlbimp.exe가 생성한 COM Interop DLL만 있으면 나머지는 Reflection으로 COM 객체의 정보를 열람할 수 있기 때문에 manifest 만드는 것을 자동화했습니다.

다음 코드는 간략하게 만들어 본 것이고,

using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;

namespace COMRegFreeManifest
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("COMRegFreeManifest.exe [com_dll_path]");
                return;
            }

            string path = args[0];

            string currentPath = Environment.CurrentDirectory;
            string dllManifestPath = Path.Combine(currentPath, Path.GetFileName(path));
            string exeManifestPath = Path.Combine(currentPath, "Sample.exe");

            string impLibPath = Path.Combine(Path.GetTempPath(), "test.dll");

            try
            {
                if (RunTlbImp(path, impLibPath) == false)
                {
                    Console.WriteLine("TLBIMP not work");
                    return;
                }

                byte[] buf = File.ReadAllBytes(impLibPath);
                Assembly asm = Assembly.ReflectionOnlyLoad(buf);

                ExportDllManifest(asm, impLibPath, dllManifestPath);
                ExportExeManifest(asm, impLibPath, dllManifestPath, exeManifestPath);
            }
            finally
            {
                if (File.Exists(impLibPath) == true)
                {
                    File.Delete(impLibPath);
                }
            }
        }
        private static void ExportExeManifest(Assembly asm, string impLibPath, string dllManifestPath, string exeManifestPath)
        {
            string manifestTemplate = @"<?xml version=""1.0"" encoding=""utf-8""?>
<asmv1:assembly manifestVersion=""1.0"" xmlns=""urn:schemas-microsoft-com:asm.v1"" xmlns:asmv1=""urn:schemas-microsoft-com:asm.v1"" xmlns:asmv2=""urn:schemas-microsoft-com:asm.v2"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">
  <assemblyIdentity version=""1.0.0.0"" name=""MyApplication.app""/>

  <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2"">
    <security>
      <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3"">
        <requestedExecutionLevel level=""asInvoker"" uiAccess=""false"" />
      </requestedPrivileges>
    </security>
  </trustInfo>
  
  <compatibility xmlns=""urn:schemas-microsoft-com:compatibility.v1"">
    <application>
    </application>
  </compatibility>
  
  <dependency>
    <dependentAssembly asmv2:dependencyType=""install"" asmv2:codebase=""{0}.manifest"">
      <assemblyIdentity name=""{0}"" version=""{1}"" type=""win32"" />
    </dependentAssembly>
  </dependency>

</asmv1:assembly>
";


            string dllName = Path.GetFileName(dllManifestPath);
            string version = asm.GetName().Version.ToString();

            string manifestText = string.Format(manifestTemplate, dllName, version);
            File.WriteAllText(exeManifestPath + ".manifest", manifestText);
        }

        private static void ExportDllManifest(Assembly asm, string impLibPath, string dllManifestPath)
        {
            string txt = GetManifestContents(asm, dllManifestPath);
            File.WriteAllText(dllManifestPath + ".manifest", txt);
        }

        static string GetManifestContents(Assembly asm, string dllManifestPath)
        { 
            string manifestTemplate = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
<assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0"">

  <assemblyIdentity version=""{0}"" name=""{1}"" type=""win32"">
  </assemblyIdentity>
  
  <file name=""{1}"">
    <comClass clsid=""{2}"" threadingModel=""Apartment"" tlbid=""{3}"" />
    <typelib tlbid=""{3}"" version=""{4}"" helpdir="""" resourceid=""0"" />
  </file>

  {5}
</assembly>
";
            string interfaceTemplate = @"
  <comInterfaceExternalProxyStub name=""{0}"" 
                                 iid=""{1}"" 
                                 proxyStubClsid32=""{{00020424-0000-0000-C000-000000000046}}"" 
                                 baseInterface=""{2}"" 
                                 tlbid=""{3}"">
  </comInterfaceExternalProxyStub>
";

            string version = asm.GetName().Version.ToString();
            string dllName = Path.GetFileName(dllManifestPath);
            string clsid = $"{{{GetClsid(asm)}}}";
            string tlbid = $"{{{GetAssemblyAttr(asm, typeof(GuidAttribute))}}}";
            string tlbVersion = GetTypeLibVersion(asm);

            StringBuilder sb = new StringBuilder();

            foreach (Type type in asm.GetTypes())
            {
                if (type.IsInterface == false || HasCoClassAttribute(type))
                {
                    continue;
                }

                string interfaceName = type.Name;
                string interfaceIid = $"{{{GetGuid(type)}}}";
                string baseInterfaceIid = GetBaseInterfaceIID(type);

                string interfaceText = string.Format(interfaceTemplate, interfaceName, interfaceIid, baseInterfaceIid, tlbid);
                sb.AppendLine(interfaceText);
            }

            string manifestText = string.Format(manifestTemplate, version, dllName, clsid, tlbid, tlbVersion, sb.ToString());

            return manifestText;
        }

        private static string GetBaseInterfaceIID(Type type)
        {
            foreach (CustomAttributeData attr in type.GetCustomAttributesData())
            {
                if (attr.Constructor.DeclaringType == typeof(TypeLibTypeAttribute))
                {
                    TypeLibTypeFlags flags = (TypeLibTypeFlags)attr.ConstructorArguments[0].Value;
                    if (flags.HasFlag(TypeLibTypeFlags.FDual))
                    {
                        return "{00020400-0000-0000-C000-000000000046}";
                    }
                    else
                    { 
                        return "{00000000-0000-0000-C000-000000000046}";
                    }
                }
            }
            return "";
        }

        private static string GetTypeLibVersion(Assembly asm)
        {
            foreach (CustomAttributeData attr in asm.GetCustomAttributesData())
            {
                if (attr.Constructor.DeclaringType == typeof(TypeLibVersionAttribute))
                {
                    return $"{attr.ConstructorArguments[0].Value}.{attr.ConstructorArguments[1].Value}";
                }
            }

            return "";
        }

        private static bool HasCoClassAttribute(Type type)
        {
            foreach (CustomAttributeData attr in type.GetCustomAttributesData())
            {
                if (attr.Constructor.DeclaringType == typeof(CoClassAttribute))
                {
                    return true;
                }
            }

            return false;
        }

        private static string GetClsid(Assembly asm)
        {
            foreach (Type type in asm.GetTypes())
            {
                foreach (CustomAttributeData attr in type.GetCustomAttributesData())
                {
                    if (attr.Constructor.DeclaringType == typeof(CoClassAttribute))
                    {
                        return GetGuid(attr.ConstructorArguments[0].Value as Type);
                    }
                }
            }

            return "";
        }

        private static string GetGuid(Type type)
        {
            foreach (CustomAttributeData attr in type.GetCustomAttributesData())
            {
                if (attr.Constructor.DeclaringType == typeof(GuidAttribute))
                {
                    return attr.ConstructorArguments[0].Value as string;
                }
            }

            return "";
        }

        private static string GetAssemblyAttr(Assembly asm, Type targetType)
        {
            foreach (CustomAttributeData attr in asm.GetCustomAttributesData())
            {
                if (attr.Constructor.DeclaringType == targetType)
                {
                    return attr.ConstructorArguments[0].Value as string;
                }
            }

            return "";
        }

        private static bool RunTlbImp(string path, string impLibPath)
        {
            ProcessStartInfo psi = new ProcessStartInfo();
            psi.FileName = GetTlbImpPath("tlbimp.exe");
            psi.Arguments = $"\"{path}\" /out:\"{impLibPath}\"";
            psi.CreateNoWindow = true;
            psi.UseShellExecute = false;

            Process newProc = Process.Start(psi);
            newProc.WaitForExit();

            return File.Exists(impLibPath);
        }

        private static string GetTlbImpPath(string toolName)
        {
            using (RegistryKey regKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\WOW6432Node\Microsoft\Microsoft SDKs\NETFXSDK", false))
            {
                foreach (string version in regKey.GetSubKeyNames())
                {
                    using (RegistryKey versionKey = regKey.OpenSubKey(version, false))
                    {
                        foreach (string tool in versionKey.GetSubKeyNames())
                        {
                            using (RegistryKey toolKey = versionKey.OpenSubKey(tool))
                            {
                                string path = toolKey.GetValue("InstallationFolder") as string;

                                string tlbimpPath = Path.Combine(path, toolName);
                                if (File.Exists(tlbimpPath) == true)
                                {
                                    return tlbimpPath;
                                }
                            }
                        }
                    }
                }
            }

            return null;
        }
    }
}

실행은 단순하게, COM DLL 파일을 전달하면 됩니다.

c:\temp> COMRegFreeManifest.exe c:\test\my_atl.dll

그럼 my_atl.dll.manifest와 Sample.exe.manifest 파일이 각각 다음과 같은 식으로 생성됩니다.


[my_atl.dll.manifest]

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">

    <assemblyIdentity version="1.0.0.0" name="my_atl.dll" type="win32">
    </assemblyIdentity>

    <file name="my_atl.dll">
        <comClass clsid="{2F71B57A-B6DF-4733-A29A-6ECA13FAE34F}" threadingModel="Apartment" tlbid="{0B2AAC68-8E4B-4BAA-85D7-4DF62A224D9F}" />
        <typelib tlbid="{0B2AAC68-8E4B-4BAA-85D7-4DF62A224D9F}" version="1.0" helpdir="" resourceid="0" />
    </file>


    <comInterfaceExternalProxyStub name="IATLSimpleObject"
                                   iid="{CB82A462-8F49-4434-987B-CB8FBC8A9115}"
                                   proxyStubClsid32="{00020424-0000-0000-C000-000000000046}"
                                   baseInterface="{00020400-0000-0000-C000-000000000046}"
                                   tlbid="{0B2AAC68-8E4B-4BAA-85D7-4DF62A224D9F}">
    </comInterfaceExternalProxyStub>


</assembly>


[Sample.exe.manifest]

<?xml version="1.0" encoding="utf-8"?>
<asmv1:assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>

    <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
        <security>
            <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
                <requestedExecutionLevel level="asInvoker" uiAccess="false" />
            </requestedPrivileges>
        </security>
    </trustInfo>

    <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
        <application>
        </application>
    </compatibility>

    <dependency>
        <dependentAssembly asmv2:dependencyType="install" asmv2:codebase="my_atl.dll.manifest">
            <assemblyIdentity name="my_atl.dll" version="1.0.0.0" type="win32" />
        </dependentAssembly>
    </dependency>

</asmv1:assembly>

오~~~ 제법 폼 나는군요. ^^ 이제 my_atl.dll.manifest 파일은 EXE 프로젝트에 포함해 "Copy to Output Directory" 옵션을 "Copy if newer"로 설정하고 Sample.exe.manifest 파일은 EXE 프로젝트 속성 창의 "Application" 범주의 "Resources" 영역에 "Manifest:" 콤보 박스에 등록해 주시면 됩니다.

(전체 프로젝트는 github에 올렸습니다. - https://github.com/stjeong/DotNetSamples/tree/master/WinConsole/COMRegFreeManifest)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 2/26/2020]

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