1

This is all TLDR, made it as short as I could.

I have a c# WPF desktop application where I use some legacy C++ library via managed C++ wrapper built for x64 and Win32. It all works fine and saved me a lots of time porting. At the same time, it has caused some awkwardness in project where I have now 90% of C# code. The C++ part no longer changes, it is there to support some 'old stuff'.

The managed C++ has Win32 and x64 configurations, while the rest of the code has x64, x86 and AnyCPU. There is always some mess in Configuration manager (Visual Studio 2017). I cannot use AnyCPU build because the presence of managed code requires specific version of DLL, so I need to build the whole workspace as x86/Win32 or x64.

So I think that I have these choices:

  1. port all to C# and enjoy the simplicity (takes time but straightforward)
  2. move the C++/CLI DLL out from the main solution and just keep the reference or create nuget package
  3. write yet another, AnyCPU wrapper that dynamically loads x64 or Win32 version of the DLL

I found lots of posts about mixing C++/C# but not extactly at that angle. So I'm thinking about a wrapper along these lines:

        String path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        path = Path.Combine(path, (IntPtr.Size == 4) ? "x86" : "x64");
        path = Path.Combine(path, "legacy.dll");

        Assembly assembly = Assembly.LoadFrom(path);
        dynamic wrapped = assembly.CreateInstance("LegacyStuff.SomeClass");
        // now use the type

The legacy C++ wrapper DLLs can be placed in relative directory (one for x64, one for x68) and we load one that matches current platform. Obviously the "LegacyStuff.SomeClass" from x64 and x86 DLL are different types, so they will be only usable as dynamic type. Unfortunately the classes in the C++ library have pretty elaborate interface with lots of properties and methods.

Edit: I have now seen more relevant info on SO about this but it takes few days before I can work further on it.

  • @HansPassant That is a good trick to load a platform-specific DLL. What I cannot immediately understand though is how to add a reference to the DLL in my AnyCPU C# project. I want to use the managed types from it, there are hundreds of classes used in a DOM that the DLL loads. – Congenital Optimist Mar 25 '20 at 10:12
  • I found a [question here](https://stackoverflow.com/questions/7727876/any-cpu-dependent-on-c-cli-dependent-on-native-c-dll-any-cpu-for-c-cli) where the answer describes use of AssemblyResolve. – Congenital Optimist Mar 31 '20 at 09:26

0 Answers0