How do I change the lookup path for .NET libraries referenced via #using in Managed C++?

半腔热情 提交于 2019-12-07 09:49:23

You can use several options - if you know in advance where the assembly will be located, you can add that path to your application's configuration file:

<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <probing privatePath="MyPath"/>
    </assemblyBinding>
  </runtime>
</configuration>

If you want to search for the assembly at runtime, you can implement a handler for AppDomain::CurrentDomain->AssemblyResolve event:

ref class AssemblyResolver
{
public:
    /// The path where the assemblies are searched
    property String^ Path
    {
        String^ get()
        { return path_; }
    }

    explicit AssemblyResolver(String^ path)
        : path_(path)
    { /* Void */ }

    Assembly^ ResolveHandler(Object^ sender, ResolveEventArgs^ args)    
    {
        // The name passed here contains other information as well
        String^ dll_name = args->Name->Substring(0, args->Name->IndexOf(','));
        String^ path = System::IO::Path::Combine(path_, dll_name+".dll");

        if ( File::Exists(path) )
            return Assembly::LoadFile(path);

        return nullptr;
    }

private:
    String^ path_;
};

and you can wire it using something like this:

AssemblyResolver^ resolver = gcnew AssemblyResolver(path);
AppDomain::CurrentDomain->AssemblyResolve += gcnew ResolveEventHandler(
    resolver, 
    &AssemblyResolver::ResolveHandler
);

Just make sure this is done before calling any methods that may use types from the assembly that has to be resolved.

Is it not the standard .net assembly resolution strategy? See here for a detailed introduction.

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