【问题标题】:Load a com DLL in c#在 C# 中加载一个 com DLL
【发布时间】:2015-10-12 06:23:29
【问题描述】:

我想在 c# 控制台应用程序中动态加载一个COM dll。

到目前为止,我已经尝试了以下代码:

// load exe with args as EXE DllName classNameTobeLoaded
try
{
 // load assembly
 Assembly Dll = Assembly.LoadFile(@"C:\My_Dir\TestComDll.dll");
 // get the type names
 foreach(Type t in Dll.GetExportedTypes())
 {
   dynamic vClassLoaded = Activator.CreateInstance(t,"Test");
   Console.WriteLine("Type Loaded");
 }

  Console.WriteLine("DLL is loaded");
}
catch (Exception ex)
{
  Console.WriteLine("Unable to load a DLL because \n" + ex.Message);
}

但在加载 dll 时出现以下错误:

{System.BadImageFormatException: The module was expected to contain an assembly manifest. (Exception from HRESULT: 0x80131018)
   at System.Reflection.RuntimeAssembly.nLoadFile(String path, Evidence evidence)
   at System.Reflection.Assembly.LoadFile(String path)
   at ThirdPartyDLLLoader.Program.Main(String[] args) in h:\Test Exe\ThirdPartyDLLLoader\ThirdPartyDLLLoader\Program.cs:line 18}

对于.NET DLL,相同的代码也可以正常工作。

谁能告诉我为什么代码不能动态加载 COM dll?

如果不是,请告诉我我该怎么做。

感谢您的任何建议和帮助。

【问题讨论】:

  • 您必须使用Tlbimp.exe 创建一个包装器。
  • COM 的工作方式与 .NET 不同。 TestComDll.dll 是否在加载前注册?
  • @Dennis 是的,我在加载之前已经注册了 dll
  • @Filburt 我也有一个 tlb,但没有使用 Tlbimp.exe 创建任何 CLR 程序集

标签: c# .net dll com


【解决方案1】:

这是无法做到的。 Assembly.LoadFrom 方法用于加载 .NET 程序集。必须注册 COM 库,然后才能使用Activator.CreateInstance 方法实例化类。

这是我访问 MS Word 的方式:

Type type = Type.GetTypeFromProgID("Word.Application");
object obj = Activator.CreateInstance(type);

【讨论】:

    【解决方案2】:

    我有一个函数加载一个类库dll

     public ICollection<Assembly> GetAssemblies(string pathOfDLL)
        {
            List<Assembly> baseAssemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();
            var controllersAssembly = Assembly.LoadFrom(pathOfDLL);
            baseAssemblies.Add(controllersAssembly);
            return baseAssemblies;
        }
    

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 2014-02-14
      • 1970-01-01
      • 2012-02-23
      • 1970-01-01
      • 1970-01-01
      • 2011-02-27
      • 2011-05-05
      • 2011-08-13
      相关资源
      最近更新 更多