应用程序在部署时无法找到非托管dll

时间:2016-07-21 14:31:56

标签: c# asp.net iis dll unmanaged

我正在运行在任何CPU模式下运行的Web API Asp.Net 4.6应用程序(虽然我也试过这个指定x64)并且它调用了一个非托管的x64 C dll。虽然我在部署到另一台服务器并在IIS或IIS Express中运行时遇到Windows错误126(无法找到指定的模块),但在Visual Studio中运行时(使用默认的IIS Express设置)可以正常工作,即使我确定DLL的路径是正确的。还有什么我可以尝试的吗?

My native Methods Wrapper:

public static class NativeMethods
{
    [DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
    public static extern IntPtr LoadLibrary(string dllToLoad);

    [DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
    public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);

    [DllImport("kernel32.dll")]
    public static extern bool FreeLibrary(IntPtr hModule);

    [DllImport("kernel32.dll", CharSet = CharSet.Ansi)]
    public static extern IntPtr GetModuleHandle(string lpModuleName);

    [DllImport("kernel32.dll")]
    public static extern uint GetLastError();
}

我的加载DLL方法:

private static void LoadDll()
    {
        UnloadDLL(); //Unload the module first

        if (string.IsNullOrEmpty(DllDirectory))
            throw new ApplicationException("DPI DLL directory not specified.");

        if (!File.Exists(DllPath))
            throw new ApplicationException("Could not find DPI DLL.");

        pDll = NativeMethods.LoadLibrary(DllPath);
        //Fails Here
        if (pDll == IntPtr.Zero)
            throw new ApplicationException(string.Format("Failed to load library <{0}> (ErrorCode: {1})", DllPath, Marshal.GetLastWin32Error())); 
    }

如果我能说得更清楚,请告诉我,谢谢!

1 个答案:

答案 0 :(得分:0)

使用Dependency Walker获取模块的依赖项列表(带路径DllPath的模块)。另外,检查是否需要在服务器上安装Visual C ++ Redistributable。

通过 ikenread :需要检查非托管DLL编译模式。如果它在调试模式下编译,它将依赖于Visual C ++ Redistributable dll的调试版本,并且它们(很可能)在生产服务器上不存在。