3

我正在尝试使用 kernal32.dll 中的几个函数。但是,当我的应用程序尝试调用第一个函数时,它会抛出一个 EntryPointNotFoundExceptionUnable 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. */
    }
}

任何关于我做错了什么以及如何让它发挥作用的想法将不胜感激。谢谢。

4

2 回答 2

8

您必须删除 ExactSpelling 属性。该函数的真实名称是SetDllDirectoryW。我还建议您使用 CharSet.Auto,使用 Ansi 是一种有损转换,可能会导致微妙的问题。XP SP1 之前的任何 Windows 版本均不提供导出功能。

于 2010-09-20T16:12:41.833 回答
1

我不太了解DllImport,但是在我的机器上删除ExactSpelling属性就可以了。

于 2010-09-20T16:16:54.790 回答