tags:

views:

90

answers:

2

I am trying to use several functions from kernal32.dll. However, when my application tries to call the first function it throws an EntryPointNotFoundException Unable to find an entry point named 'SetDllDirectory' in DLL 'kernel32.dll'.

public class MyClass
{
    /// <summary>
    /// Use to interface to kernel32.dll for dynamic loading of similar DLLs.
    /// </summary>
    internal static class UnsafeNativeMethods
    {
        [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
        internal static extern IntPtr LoadLibrary(string lpFileName);

        [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
        internal static extern bool SetDllDirectory(string lpPathName);

        [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
        internal static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
    }

    private void MyFunc()
    {
        if (UnsafeNativeMethods.SetDllDirectory(_location) == false) // <-- Exception thrown here.
        {
            throw new FileNotFoundException(_location);
        }

        /* Some code. */

        _dllHandle = UnsafeNativeMethods.LoadLibrary(_fullPath);

        /* Some more code. */

        _fptr = UnsafeNativeMethods.GetProcAddress(_dllHandle, _procName);

        /* Yet even more code. */
    }
}

Any thoughts on what I am doing wrong and how I can get it working would be greatly appreciated. Thanks.

+7  A: 

You will have to remove the ExactSpelling property. The real name of the function is SetDllDirectoryW. I also recommend you use CharSet.Auto, using Ansi is a lossy conversion that can cause subtle problems. The export is not available in any Windows version prior to XP SP1.

Hans Passant
A: 

I do not know much about DllImport, but on my machine removing ExactSpelling attribute just do it.

tia