為什麼不能在DllMain中呼叫LoadLibrary,FreeLibrary以及呼叫CreateThread?

時間 2021-05-31 05:17:37

1樓:BianChengNan

請參考DllMain : a horror story

我感覺如果是兩個很單純的dll 應該不會有事!雖然微軟不對這種行為做保證!but who cares!!! I just Load it in dllmain!!!

2樓:Sting

簡單的說,DllMain的呼叫前後系統加了一把loader-lock,導致很多API都不能呼叫,在DllMain裡做的事情越少越好,否則容易死鎖。解決你的問題,可以把dll 2靜態鏈結到dll1,只要你在dll 1中隨便什麼函式呼叫一下dll 2裡匯出的函式就行。或者你也可以用微軟的Detours庫里的setdll工具,讓dll 1強行依賴dll 2,這樣系統載入dll 1時就會載入dll 2。

詳細的解釋看微軟的這篇文件:Best Practices for Creating DLLs

裡面提到了哪些事不能做,其中就有LoadLibrary:

You should never perform the following

tasks from withinDllMain:

CallLoadLibraryorLoadLibraryEx(either directly or indirectly). This can cause a deadlock or a crash.

Synchronize with other threads.

This can cause a deadlock.

Acquire a synchronization

object that is owned by code that is waiting to acquire the loader lock. This

can cause a deadlock.

Initialize COM threads by usingCoInitializeEx. Under certain

conditions, this function can callLoadLibraryEx.

Call the registry functions.

These functions are implemented in Advapi32.dll. If Advapi32.dll is not

initialized before your DLL, the DLL can access uninitialized memory and cause

the process to crash.

CallCreateProces. Creating a process can load another DLL.

CallExitThread.Exiting a

thread during DLL detach can cause the loader lock to be acquired again,

causing a deadlock or a crash.

CallCreateThread. Creating a thread can work if you do not synchronize

with other threads, but it is risky.

Create a named pipe or other

named object (Windows 2000 only). In Windows 2000, named objects are provided

by the Terminal Services DLL. If this DLL is not initialized, calls to the DLL

can cause the process to crash.

Use the memory management

function from the dynamic C Run-Time (CRT). If the CRT DLL is not initialized,

calls to these functions can cause the process to crash.

Call functions in User32.dll or

Gdi32.dll. Some functions load another DLL, which may not be initialized.

Use managed code.

UE4 藍圖 delay 為什麼不能 在for 中連續呼叫

delay是非阻塞呼叫,delay後的操作是相當於定時呼叫。到delay就過了。如果delay能用到for迴圈中,那delay就不是一段時間後執行,而是等待一段時間,並阻塞當前程序,那樣介面就會卡死,因為所有邏輯都被阻塞。 南京周潤發 有乙個簡單的方法可以解答疑惑,可以把BaseEngine.ini...

為什麼樂譜中只用 E調這個說法不用 D調呢?

煊赫 bE 3降 和 D 9公升 調都存在,F 6公升 和bG 6降 調也存在,CDEFGAB這七個加上公升和降都可以存在,這才是理論 樂理 說你不懂樂理的那個人也就是個半吊子。調 在當今流行樂裡通常說的是西洋大調,調的命名是根據主音來的,主音是 D就是 D調,主音是bE就是bE調,所以按照理論來說...

為什麼不能在背後說別人壞話?

職場火鍋 職場潛規則有千萬條,哪一條都夠深的,遇到就剝一層皮。但是,關於做人做事的潛規則,人人都有自己的哲學,仁者見仁智者見智。行走職場,最大的愚蠢,就是交淺言深,高估與別人的關係,自己掏心掏肺說真話,卻被別人當傻瓜當槍使。職場任何關係,在利益面前都不堪一擊。職場做人做事,繞不開這 四個 關係矩陣,...