2009-08-28 69 views
7

在Windows中,導入ctypes模塊時,ctypes.cdll.msvcrt對象會自動存在,它代表msvcrt Microsoft C++運行時庫according to the docsctypes中的msvcrt的不同版本

但是,我注意到,還有一個find_msvcrt函數,它將"return the filename of the VC runtype library used by Python"

它進一步指出,"If you need to free memory, for example, allocated by an extension module with a call to the free(void *), it is important that you use the function in the same library that allocated the memory."

所以我的問題是,什麼是ctypes.cdll.msvcrt庫,我已經和我可以用find_msvcrt功能加載之間的差異?在特定情況下,他們可能不是同一個圖書館?

+1

相關:[在Windows上訪問msvcrt的方式有什麼區別?](https://stackoverflow.com/q/30790494/4279) – jfs 2017-10-17 10:37:51

回答

10

ctypes.cdll.msvcrt自動存在,但ctypes.cdll.anything自動存在,並在第一次訪問時加載,加載anything.dll。所以ctypes.cdll.msvcrt加載msvcrt.dll,這是作爲Windows的一部分發布的庫。它不是Python鏈接的C運行庫,所以你不應該從msvcrt調用malloc/free。

例如,對於Python 2.6/3.1,您應該使用ctypes.cdll.msvcr90。由於這將隨時間而改變,因此find_msvcrt()會給出您應該真正使用的庫的名稱(然後通過ctypes.CDLL加載)。

下面是幾種不同版本的Microsoft CRT的名稱,作爲MSC,VC++,平臺SDK或Windows的一部分在各個點發布:crtdll.dll,msvcrt.dll,msvcrt4.dll,msvcr70。 dll,msvcr71.dll,msvcr80.dll,msvcr90.dll。

+0

謝謝!我沒有花太多時間在Windows環境下編程,所以這種細節非常有幫助。 – 2009-08-28 19:35:42

+4

所以爲了完整性 - ctypes.cdll [ctypes.util.find_msvcrt()]應該返回正確的CRT句柄。 – 2009-12-23 00:45:29