1

我正在尝试使用相同的 DllImport 调用加载我的 32/64 位本机 dll。

目录结构:

根:

  • 应用程序.exe
  • /win64/
    • stb_image.dll
  • /win32/
    • stb_image.dll

我尝试使用此解决方案,但您看不到成功。

例如这个函数调用:

[DllImport("stb_image.dll")]
private static extern IntPtr stbi_load(string filename, ref int x, ref int y, ref int n, int req_comp);

但它不起作用,因为我得到一个 DllNotFoundException。

我使用 SetDllDirectory 的方式:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        SetUnmanagedDllDirectory();

        GameConfiguration config = new GameConfiguration();
        config.FPSTarget = 60;
        config.FixedFPS = true;
        config.Resizable = false;

        TestGame game = new TestGame(config);
        game.Run();
    }

    public static void SetUnmanagedDllDirectory()
    {
        string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        path = Path.Combine(path, IntPtr.Size == 8 ? "win64 " : "win32");
        if (!SetDllDirectory(path)) throw new System.ComponentModel.Win32Exception();
    }

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern bool SetDllDirectory(string path);
}

这是我程序中的第一次调用,所以它应该设置正确的路径。它也返回真。

但是,如果我将(在我的情况下)64 位本机 dll 放在 exe 的目录中,那么即使我将 DllDirectory 设置为不同的路径,它也可以工作。

有什么帮助吗?

4

1 回答 1

0

kernel32 开发出了点问题。但是有一个解决方法是通过为当前进程会话设置 PATH 环境变量。

string dllFolder = "<somewhere>";

string path = Environment.GetEnvironmentVariable("PATH");
Environment.SetEnvironmentVariable("PATH", dllFolder + ";" + path);

在 PATH 变量中注册文件夹后,LoadLibrary 可以完美运行并从指定的路径加载 Dll(s)。

于 2017-07-28T17:09:21.960 回答