6

I am currently writing a helper library that connects to shop floor PLCs via Software Toolbox's TopServer.

The TopServer library has separate versions for x86 and x64 architectures and I want to load the appropriate version at runtime using late binding based on the CPU architecture of the calling code. The methods in the two libraries have the same signatures.

I can use reflection to load the relevant object using the below code but I am wondering what is the best method of using this instance in the calling code.

public class LateBinding
{
    public static T GetInstance<T>(string dllPath, string fullyQualifiedClassName) where T : class
    {
        Assembly assembly = System.Reflection.Assembly.LoadFile(dllPath);
        Type t = assembly.GetType(fullyQualifiedClassName);

        return (T)Activator.CreateInstance(t);
    }
}

As I'm late binding I don't get the types pre-runtime so was thinking that creating an interface based on the libraries method signatures would be a good way to implement both version.

Does anyone have a view on this method or recommendations on other methods?

Phil Murray
  • 6,396
  • 9
  • 45
  • 95

1 Answers1

0

If the target DLLs only vary by the target architecture and the assemblies are not strongly named, an interface is not necessary.

My suggestion is to name them *_64.dll and *_86.dll respectively and pick one to compile against.

At runtime, all you need to do is System.Reflection.Assembly.LoadFile the correct file.

Gusdor
  • 14,001
  • 2
  • 52
  • 64
  • The problem with compiling to a specific version is that that compiled dll will not work on the other architecture. If I compile to x86 the Software Toolbox dll will not run on a x64 architecture – Phil Murray Nov 14 '13 at 13:49
  • Are you compiling **your** assemblies as 'Any CPU', 'x86' or 'x64'? – Gusdor Nov 14 '13 at 13:50
  • Any Cpu would be the ideal. – Phil Murray Nov 14 '13 at 13:51
  • @PhilMurray When you build, you are always going to have to target one of the assemblies. Is 64bit even required? I always compile everything to x86 if I have unmanaged/architecture specific code. Keeps things simple. You can do this by changing your entry assembly to x86. – Gusdor Nov 14 '13 at 13:53
  • Understand that sentiment but this assembly has other dependencies which would need to be changed to x86. Changing all the dependencies is not something I want to do. – Phil Murray Nov 14 '13 at 14:46
  • @PhilMurray If the dependencies are .net assemblies, you can leave them as 'Any CPU' and they will load just fine - as long as the _entry_ assembly is x86. – Gusdor Nov 14 '13 at 15:35
  • That's the problem, this will be part of a library where I would prefer not to target x86 specifically. – Phil Murray Nov 14 '13 at 15:38