Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Managed C++ and AnyCPU

I have a Managed C++ dll that I am referencing from a C# project. The C# project will be compiled as AnyCPU. Is there any way to compile a 32-bit and 64-bit version of the Managed C++ dll and then tell the C# project at runtime to load the correct one depending on which architecture it is being run?

like image 522
Dirk Dastardly Avatar asked May 02 '12 12:05

Dirk Dastardly


2 Answers

The trick to getting the AnyCPU dll to play with the C++ dll, is at runtime make sure the assembly cannot load the C++ dll and then subscribe to the AppDomain AssemblyResolve event. When the assembly tries to load the dll and fails, then your code has the opportunity to determine which dll needs to be loaded.

Subscribing to the event looks something like this:

System.AppDomain.CurrentDomain.AssemblyResolve += Resolver;

Event handler looks something like this:

System.Reflection.Assembly Resolver(object sender, System.ResolveEventArgs args)
{
     string assembly_dll = new AssemblyName(args.Name).Name + ".dll";
     string assembly_directory = "Parent directory of the C++ dlls";

     Assembly assembly = null;
     if(Environment.Is64BitProcess)
     {
            assembly = Assembly.LoadFrom(assembly_directory + @"\x64\" + assembly_dll);
     }
     else
     {
            assembly = Assembly.LoadFrom(assembly_directory + @"\x86\" + assembly_dll);
     }
     return assembly;
}

I have created a simple project demonstrating how to access C++ functionality from an AnyCPU dll.

https://github.com/kevin-marshall/Managed.AnyCPU

like image 157
Kevin Marshall Avatar answered Oct 21 '22 01:10

Kevin Marshall


I don't know how do you 'reference' the C++ dll(P/Invoke vs .net assembly reference) but either way you could swap the two versions of the .dll at installation time.

like image 35
Ventsyslav Raikov Avatar answered Oct 20 '22 23:10

Ventsyslav Raikov