Matthiee
Matthiee

Reputation: 493

SetDllDirectory not working ( DllNotFoundException )

I'm trying to load my 32/64 bit native dll's using the same DllImport call.

Directory structure:

root:

I tried using this solution but as you can see no succes.

For example this function call:

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

But it doesn't work as I get an DllNotFoundException.

The way I'm using 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);
}

It's the first call in my program so it should've set the correct path. It also returns true.

But if I put the (in my case) 64 bit native dll in the exe's directory then it works even tho I set the DllDirectory to a different path.

Any help?

Upvotes: 1

Views: 3244

Answers (2)

Apollo Y
Apollo Y

Reputation: 1

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

good luck

Upvotes: -1

Alfishe
Alfishe

Reputation: 3680

Something went wrong with kernel32 development. But there is a workaround via setting PATH environment variable for the current process session.

string dllFolder = "<somewhere>";

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

After registering the folder in PATH variable, LoadLibrary works flawlessly and loads Dll(s) from the path specified.

Upvotes: 0

Related Questions