2015-10-12 60 views
0

我想在c#console应用程序中动态地加载一个COM dll。在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吗?

如果不是,你可以告诉我怎样才能做到这一点。

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

+0

您必须使用[Tlbimp.exe](https://msdn.microsoft.com/en-us/library/tt0cf3sx%28v=vs.110%29.aspx)创建包装。 – Filburt

+0

COM的工作方式与.NET不同。 TestComDll.dll在加载之前注册了吗? – Dennis

+0

@丹尼斯是的我已经在加载之前注册了dll –

回答

-1

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

这是我如何访问MS Word中:

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

什么是'CreateObject'方法?你能提供一个链接吗? – Dennis

0

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

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

希望它能帮助!