2012-03-28 65 views
0

我有一些舊的代碼似乎無法在64位Windows 7上工作。沒有嘗試32位Windows 7,但絕對適用於32位XP。較舊的代碼無法獲得DLL的句柄

代碼最初是從這篇文章http://www.codeproject.com/KB/cs/DynamicInvokeCSharp.aspx

我讀過this question其中指出,kernel32.dll中仍然存在的。

[DllImport("kernel32.dll", EntryPoint = "LoadLibrary")] 
private static extern int LoadLibrary([MarshalAs(UnmanagedType.LPStr)] string lpLibFileName); 

[DllImport("kernel32.dll", EntryPoint = "GetProcAddress")] 
private static extern IntPtr GetProcAddress(int hModule, [MarshalAs(UnmanagedType.LPStr)] string lpProcName); 

[DllImport("kernel32.dll", EntryPoint = "FreeLibrary")] 
private static extern bool FreeLibrary(int hModule); 

[DllImport("kernel32.dll")] 
private static extern bool SetDllDirectory([M 

arshalAs(UnmanagedType.LPStr)] string lpPathName);

,這是它是如何使用:

public void Init(string dllName) 
{ 
    DllName = dllName; 
    SetDllDirectory(Path.GetDirectoryName(dllName)); 
    hModule = LoadLibrary(Path.GetFileName(dllName)); 
    if (hModule == 0) 
     throw new Exception("Cannot load dll " + dllName); 
} 

我得到的問題是,LoadLibrary總是把手返回0

我也曾嘗試hModule = LoadLibrary(dllName);

任何人都可以扔在爲什麼它可能無法正常工作任何光線,或者我應該不是做?

+0

得到一個稍微有用例外嘗試編譯和運行應用程序在64位機器上以32位模式運行。這只是一個猜測;但我認爲有一個問題P /從64位.net應用程序調用32位DLL。 – Alxandr 2012-03-28 10:06:55

+0

@Alxandr謝謝,我忘了提及所有項目的程序集都已經在x86上。 – weston 2012-03-28 10:09:55

+0

這可能是一個嘗試從x64程序或缺少的DLL加載x86 dll的問題,但嘗試向您的'DllImport'語句添加'SetLastError = true',然後調用'Marshal.GetLastWin32Error()'以從'LoadLibrary' – jeffora 2012-03-28 10:10:03

回答

1

(按上回答評論)

大多數的Windows API函數調用一個叫SetLastError()程序來表示失敗的原因。在.NET中使用DllImport時,您可以將屬性添加到屬性中,以明確指示函數應該保留最後一個錯誤(我對默認行爲不是100%確定,但明確保證它會發生)。

如:

[DllImport("kernel32.dll", EntryPoint = "LoadLibrary", SetLastError = true)] 
private static extern int LoadLibrary([MarshalAs(UnmanagedType.LPStr)] string lpLibFileName); 

然後,您可以通過調用Marshal.GetLastWin32Error()得到從託管代碼中的錯誤代碼,或通過拋出一個Win32Exception這樣throw new Win32Exception(Marshal.GetLastWin32Error())