SetDllDirectory无法正常工作(DllNotFoundException)

时间:2016-03-22 11:26:49

标签: c# .net windows dllnotfoundexception setdlldirectory

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

目录结构:

根:

  • application.exe
  • / Win64的/
    • stb_image.dll
  • /的Win32 /
    • stb_image.dll

我尝试使用this solution,但你看不到任何成功。

例如这个函数调用:

[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);
}

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

但是如果我把(在我的情况下)64位原生dll放在exe的目录中,那么它甚至可以将DllDirectory设置为不同的路径。

有任何帮助吗?

1 个答案:

答案 0 :(得分:0)

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

{{1}}

在PATH变量中注册文件夹后,LoadLibrary可以正常工作并从指定的路径加载Dll。

相关问题