views:

71

answers:

5

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?

A: 

How about doing a P/Invoke to `LoadLibrary'?

Steven Sudit
and waht would you do with the obtained handle then? GetProcAddress and what's next?
Eugene Mayevski 'EldoS Corp
Nothing. If I got the handle, I'd release it and call through the extern that uses that DLL name. If not, I'd try with the next DLL.
Steven Sudit
A: 

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.

Eugene Mayevski 'EldoS Corp
A: 

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.

Jonathan
There's no reason for the DLL's to export different names: you can alias them on reference.
Steven Sudit
A: 

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.

Serapth
A: 

I think I found a workable solution:

http://stackoverflow.com/questions/541085/c-check-that-a-file-destination-is-valid

Thanks, everyone, for your input!

Jim Fell