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?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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
回答2:
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.