In Windows, the ctypes.cdll.msvcrt
object automatically exists when I import the ctypes module, and it represents the msvcrt
Microsoft C++ runtime library according to the docs.
However, I notice that there is also a find_msvcrt function which will "return the filename of the VC runtype library used by Python"
.
It further states, "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."
So my question is, what's the difference between the ctypes.cdll.msvcrt
library that I already have and the one which I can load with the find_msvcrt
function? Under what specific circumstances might they not be the same library?
It's not just that ctypes.cdll.msvcrt
automatically exists, but ctypes.cdll.anything
automatically exists, and is loaded on first access, loading anything.dll
. So ctypes.cdll.msvcrt
loads msvcrt.dll
, which is a library that ships as part of Windows. It is not the C runtime that Python links with, so you shouldn't call the malloc/free from msvcrt
.
For example, for Python 2.6/3.1, you should be using ctypes.cdll.msvcr90
. As this will change over time, find_msvcrt()
gives you the name of the library that you should really use (and then load through ctypes.CDLL
).
Here are the names of a few different versions of the Microsoft CRT, released at various points as part of MSC, VC++, the platform SDK, or Windows: crtdll.dll, msvcrt.dll, msvcrt4.dll, msvcr70.dll, msvcr71.dll, msvcr80.dll, msvcr90.dll.