Managed C++ and AnyCPU

白昼怎懂夜的黑 提交于 2019-12-06 22:27:35

问题


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.



来源:https://stackoverflow.com/questions/10413590/managed-c-and-anycpu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!