简体   繁体   中英

Dynamically Loading DLLs at Runtime

I'm working on a C# application that supports two communications interfaces, each supported by its own DLL. Each DLL contains the same function names, but their implementation varies slightly depending on the supported interface. As it is, users will typically have only one DLL installed on their machine, not both. The DLL for the old interface is imported like this:

[DllImport("myOldDll.dll", 
           CharSet = CharSet.Auto, 
           CallingConvention = CallingConvention.StdCall)]
public static extern int MyFunc1( void );
public static extern int MyFunc2( void );
public static extern int MyFunc3( void );

Would this be a valid way to attempt to bring in either DLL?

[DllImport("myOldDll.dll", 
       CharSet = CharSet.Auto, 
       CallingConvention = CallingConvention.StdCall)]
[DllImport("myNewDll.dll", 
       CharSet = CharSet.Auto, 
       CallingConvention = CallingConvention.StdCall)]
public static extern int MyFunc1( void );
public static extern int MyFunc2( void );
public static extern int MyFunc3( void );

Ideally, I suppose it would be nice to detect a missing DLL and load the second DLL if the attempt to load the first fails. Is there a graceful way to do that?

P /调用“ LoadLibrary”怎么样?

In .NET 1.1 you would need to create a proxy unmanaged DLL (write it in C or Delphi or ... ) and call it's methods, and that unmanaged DLL would do the rest. In .NET 2.0 and later you use Assembly.LoadFile() and further. Not as elegant as just declarations you attempted to use, and requires quite a lot of coding. So I'd suggest a proxy way if possible.

也许您应该给从这两个DLL导入的方法赋予不同的名称,然后在程序中有一个指向另一个或另一个的委托(以适当的为准),并仅调用该委托。

It sounds like you would be best served re-architecting to a modular plugin style interface.

There are a billion and a half examples of this on the web, like this one . In a nutshell though, you use LoadAssembly() on a directory of DLLs, then cast back to your common base interface.

I think I found a workable solution:

C# check that a file destination is valid

Thanks, everyone, for your input!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM