Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different versions of msvcrt in ctypes

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?

like image 653
Eli Courtwright Avatar asked Aug 28 '09 18:08

Eli Courtwright


People also ask

What is CDLL Msvcrt?

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.

What is ctypes CDLL?

ctypes is a foreign function library for Python. It provides C compatible data types, and allows calling functions in DLLs or shared libraries. It can be used to wrap these libraries in pure Python.

Does ctypes work with C++?

ctypes is the de facto standard library for interfacing with C/C++ from CPython, and it provides not only full access to the native C interface of most major operating systems (e.g., kernel32 on Windows, or libc on *nix), but also provides support for loading and interfacing with dynamic libraries, such as DLLs or ...

What is C_char_p?

c_char_p is a subclass of _SimpleCData , with _type_ == 'z' . The __init__ method calls the type's setfunc , which for simple type 'z' is z_set . In Python 2, the z_set function (2.7. 7) is written to handle both str and unicode strings.


1 Answers

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.

like image 119
Martin v. Löwis Avatar answered Sep 30 '22 16:09

Martin v. Löwis