Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikibooksThe Free Textbook Project
Search

Python Programming/Extending with ctypes

From Wikibooks, open books for an open world
<Python Programming
Previous: Extending with PyrexIndexNext: Extending with Perl


ctypes[1] is aforeign function interface module for Python (included with Python 2.5 and above), which allows you to load in dynamic libraries and call C functions. This is not technically extending Python, but it serves one of the primary reasons for extending Python: to interface with external C code.

Basics

[edit |edit source]

A library is loaded using thectypes.CDLL function. After you load the library, the functions inside the library are already usable as regular Python calls. For example, if we wanted to forego the standard Python print statement and use the standard C library function,printf, you would use this:

fromctypesimport*libName='libc.so'# If you're on a UNIX-based systemlibName='msvcrt.dll'# If you're on Windowslibc=CDLL(libName)libc.printf("Hello, World!\n")

Of course, you must use the libName line that matches your operating system, and delete the other. If all goes well, you should see the infamous Hello World string at your console.

Getting Return Values

[edit |edit source]

ctypes assumes, by default, that any given function's return type is a signed integer of native size. Sometimes you don't want the function to return anything, and other times, you want the function to return other types. Every ctypes function has an attribute calledrestype. When you assign a ctypes class torestype, it automatically casts the function's return value to that type.

Common Types

[edit |edit source]
ctypes nameC typePython typeNotes
NonevoidNonethe None object
c_boolC99 _Boolbool
c_bytesigned charint
c_charsigned charstrlength of one
c_char_pchar *str
c_doubledoublefloat
c_floatfloatfloat
c_intsigned intint
c_longsigned longlong
c_longlongsigned long longlong
c_shortsigned shortlong
c_ubyteunsigned charint
c_uintunsigned intint
c_ulongunsigned longlong
c_ulonglongunsigned long longlong
c_ushortunsigned shortint
c_void_pvoid *int
c_wcharwchar_tunicodelength of one
c_wchar_pwchar_t *unicode
Previous: Extending with PyrexIndexNext: Extending with Perl
Retrieved from "https://en.wikibooks.org/w/index.php?title=Python_Programming/Extending_with_ctypes&oldid=3676274"
Category:

[8]ページ先頭

©2009-2025 Movatter.jp