开发者

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 = Calling开发者_如何学运维Convention.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?


How about doing a P/Invoke to `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.


Perhaps you should give the methods imported from either DLL different names, and then have a delegate in your program that you point to one or the other (whichever is appropriate), and only call the delegate.


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜