【问题标题】:Resolving native libraries inside WinRT package解析 WinRT 包内的本机库
【发布时间】:2014-05-26 10:39:25
【问题描述】:

考虑以下解决方案结构:Windows Store C# 应用程序 + 2 个本机库 PInvokeServer 和 PInvokeServer1。原生库代码:

// PInvokeServer1
PINVOKESERVER1_API int TestFunction1(void)
{
    return 5;
}

// PInvokeServer
PINVOKESERVER_API int TestFunction(void)
{
    return TestFunction1();
}

这两个函数都是extern C。 PInvokeServer 依赖于 PInvokeServer1(使用链接器依赖项)。 PInvokeServer.dll 和 PInvokeServer1.dll 通过构建操作内容添加到 C# 项目中,因此它们是应用程序包的一部分。 C# 声明:

    const string dllName = @"Native\PInvokeServer.dll";
    const string dllName1 = @"Native\PInvokeServer1.dll";

    [System.Runtime.InteropServices.DllImport(dllName, CallingConvention = CallingConvention.Cdecl)]
    public static extern int TestFunction();

    [System.Runtime.InteropServices.DllImport(dllName1, CallingConvention = CallingConvention.Cdecl)]
    public static extern int TestFunction1();

案例 1,不起作用(未找到模块):

    TestFunction();

案例 2,有效:

    TestFunction1();

案例 3,有效:

    TestFunction1();
    TestFunction();

案例 1:当 PInvoke 尝试加载 PInvokeServer.dll 时,它无法解析本机运行时依赖,PInvokeServer1.dll 未加载,并且我得到 Module not found 异常。例如,将 PInvokeServer1.dll 放置到 System32 目录没有帮助。

案例 2:PInvoke 能够直接加载 PInvokeServer1.dll。

案例3,一旦PInvokeServer1.dll加载完成,PInvokeServer.dll也可以加载成功。

我是我真正的程序,我有依赖于其他几个库的本地 C 库。所有这些库都添加到 C# Store 应用程序包中。但是无法加载高级库,因为 PInvoke 无法加载依赖项。我能想到的唯一方法是使用LoadLibrary PInvoke 调用加载低级库,最后使用PInvoke 调用高级库。有没有更好的办法?

【问题讨论】:

    标签: c# dll windows-8 pinvoke loadlibrary


    【解决方案1】:

    在桌面应用程序中,您可以使用AddDllDirectorySetDllDirectory 来修改搜索路径。但在 Windows 应用商店应用程序中,您无法使用这些功能。所以我看到了两个选择:

    1. 将两个 DLL 放在与可执行文件相同的目录中。在一定程度上,这是最简单、最安全的解决方案。可执行文件的目录始终是搜索的第一个位置,因此您可以确保加载正确的 DLL。
    2. 在调用任一 DLL 中的任何函数之前,调用 LoadLibrary 将绝对路径传递给 DLL 以将它们加载到进程中。在PInvokeServer 之前加载PInvokeServer1。更改您的 p/invoke 声明以仅指定 DLL 文件名。也就是说,从 p/invoke 声明中删除 Native 目录。通过显式调用LoadLibrary,您可以确保将两个DLL 加载到进程中。然后对 p/invoke 函数的后续调用将导致使用已加载的 DLL。

    【讨论】:

    • 谢谢,将原生库放到 C# 项目目录中解决了这个问题。使用LoadLibrary 显式加载也可以,但是当库与可执行文件位于同一目录时,就不需要了。
    猜你喜欢
    • 1970-01-01
    • 2017-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-24
    • 1970-01-01
    • 2017-02-22
    相关资源
    最近更新 更多