gpt4 book ai didi

.net - 从非托管 C++ 动态加载混合模式 C++/CLI .dll(和依赖项)

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:58:27 24 4
gpt4 key购买 nike

我有一个托管 C++ 程序集,我正在通过标准 LoadLibrary() 调用在非托管 C++ 应用程序中动态加载。托管 C++ 程序集依赖于多个托管 (C#) 程序集。一切正常,直到我将所有托管程序集移动到非托管应用程序的子目录中。举例说明:

  • 托管 C++ .dll (MyCoolDll.dll)

    • 依赖于 DotNetDll1.dll
    • 依赖于 DotNetDll2.dll
  • 非托管 C++ 应用 (MyCoolApp.exe)

    • 通过 LoadLibrary("MyCoolDll.dll") 加载 MyCoolDll.dll

这工作正常,直到我将 MyCoolDll.dll、DotNetDll1.dll 和 DotNetDll2.dll 移动到/someSubDirectory(MyCoolApp.exe 中的代码更新为 LoadLibrary("someSubDirectory/MyCooldll.dll")

我猜当加载 MyCoolDll.dll 时,它试图在工作目录中找到 DotNetDll1.dll 和 DotNetDll2.dll,而不是它所在的目录。

我如何告诉 MyCoolDll.dll 它的依赖项位于子目录中?它是一个在非托管应用程序内部运行的库,所以我认为我不能在 app.config 或其他任何内容中指定它?

最佳答案

我认为您正在寻找的是自定义程序集解析器。我不得不使用一个来完成我认为您正在尝试做的事情——我想在一个文件夹中找到一些 DLL,该文件夹不在初始非托管 DLL(最终加载托管代码)的树中。

第 1 步是创建一个函数,您可以调用它来设置解析器:

void PrepareManagedCode()
{
// Set up our resolver for assembly loading
AppDomain^ currentDomain = AppDomain::CurrentDomain;
currentDomain->AssemblyResolve += gcnew ResolveEventHandler(currentDomain_AssemblyResolve);
} // PrepareManagedCode()

然后是解析器。这个例子有一个全局的 ourFinalPath,在你的情况下,它是你使用的额外文件夹:

/// <summary>
/// This handler is called only when the CLR tries to bind to the assembly and fails
/// </summary>
/// <param name="sender">Event originator</param>
/// <param name="args">Event data</param>
/// <returns>The loaded assembly</returns>
Assembly^ currentDomain_AssemblyResolve(Object^ sender, ResolveEventArgs^ args)
{
sender;

// If this is an mscorlib, do a bare load
if (args->Name->Length >= 8 && args->Name->Substring(0, 8) == L"mscorlib")
{
return Assembly::Load(args->Name->Substring(0, args->Name->IndexOf(L",")) + L".dll");
}

// Load the assembly from the specified path
String^ finalPath = nullptr;
try
{
finalPath = gcnew String(ourAssemblyPath) + args->Name->Substring(0, args->Name->IndexOf(",")) + ".dll";
Assembly^ retval = Assembly::LoadFrom(finalPath);
return retval;
}
catch (...)
{
}

return nullptr;
}

关于.net - 从非托管 C++ 动态加载混合模式 C++/CLI .dll(和依赖项),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7016663/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com