public marks

PUBLIC MARKS from pvergain with tags python & libraries

28 January 2007 23:45

13 New, Improved, and Removed Modules

The ctypes package, written by Thomas Heller, has been added to the standard library. ctypes lets you call arbitrary functions in shared libraries or DLLs. Long-time users may remember the dl module, which provides functions for loading shared libraries and calling functions in them. The ctypes package is much fancier. To load a shared library or DLL, you must create an instance of the CDLL class and provide the name or path of the shared library or DLL. Once that's done, you can call arbitrary functions by accessing them as attributes of the CDLL object. import ctypes libc = ctypes.CDLL('libc.so.6') result = libc.printf("Line of outputn") Type constructors for the various C types are provided: c_int, c_float, c_double, c_char_p (equivalent to char *), and so forth. Unlike Python's types, the C versions are all mutable; you can assign to their value attribute to change the wrapped value. Python integers and strings will be automatically converted to the corresponding C types, but for other types you must call the correct type constructor. (And I mean must; getting it wrong will often result in the interpreter crashing with a segmentation fault.) You shouldn't use c_char_p with a Python string when the C function will be modifying the memory area, because Python strings are supposed to be immutable; breaking this rule will cause puzzling bugs. When you need a modifiable memory area, use create_string_buffer(): s = "this is a string" buf = ctypes.create_string_buffer(s) libc.strfry(buf) C functions are assumed to return integers, but you can set the restype attribute of the function object to change this: >>> libc.atof('2.71828') -1783957616 >>> libc.atof.restype = ctypes.c_double >>> libc.atof('2.71828') 2.71828