Larik pointer fungsi python

adalah pustaka fungsi asing untuk Python. Ini menyediakan tipe data yang kompatibel dengan C, dan memungkinkan fungsi pemanggilan di DLL atau pustaka bersama. Ini dapat digunakan untuk membungkus pustaka ini dengan Python murni

tutorial ctypes

Catatan. Contoh kode dalam tutorial ini digunakan untuk memastikan bahwa mereka benar-benar berfungsi. Karena beberapa contoh kode berperilaku berbeda di Linux, Windows, atau macOS, mereka berisi arahan doctest dalam komentar

Catatan. Beberapa contoh kode mereferensikan tipe ctypes. Pada platform di mana

>>> windll.kernel32.GetModuleHandleA(32)  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: exception: access violation reading 0x00000020
>>>
4 itu adalah alias untuk. Jadi, Anda tidak perlu bingung jika dicetak jika Anda mengharapkannya - sebenarnya jenisnya sama

Memuat pustaka tautan dinamis

mengekspor cdll, dan pada Windows objek windll dan oledll, untuk memuat pustaka tautan dinamis

Anda memuat pustaka dengan mengaksesnya sebagai atribut objek ini. cdll memuat pustaka yang mengekspor fungsi menggunakan konvensi pemanggilan

>>> windll.kernel32.GetModuleHandleA(32)  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: exception: access violation reading 0x00000020
>>>
9 standar, sedangkan pustaka windll memanggil fungsi menggunakan konvensi pemanggilan
>>> c_int()
c_long(0)
>>> c_wchar_p("Hello, World")
c_wchar_p(140018365411392)
>>> c_ushort(-3)
c_ushort(65533)
>>>
0. oledll juga menggunakan konvensi pemanggilan
>>> c_int()
c_long(0)
>>> c_wchar_p("Hello, World")
c_wchar_p(140018365411392)
>>> c_ushort(-3)
c_ushort(65533)
>>>
0, dan menganggap fungsi mengembalikan kode kesalahan
>>> c_int()
c_long(0)
>>> c_wchar_p("Hello, World")
c_wchar_p(140018365411392)
>>> c_ushort(-3)
c_ushort(65533)
>>>
2 Windows. Kode kesalahan digunakan untuk memunculkan pengecualian secara otomatis saat pemanggilan fungsi gagal

Berubah di versi 3. 3. Kesalahan Windows digunakan untuk menaikkan , yang sekarang menjadi alias dari.

Berikut adalah beberapa contoh untuk Windows. Perhatikan bahwa

>>> c_int()
c_long(0)
>>> c_wchar_p("Hello, World")
c_wchar_p(140018365411392)
>>> c_ushort(-3)
c_ushort(65533)
>>>
_6 adalah pustaka C standar MS yang berisi sebagian besar fungsi C standar, dan menggunakan konvensi pemanggilan cdecl

>>> from ctypes import *
>>> print(windll.kernel32)  
<WinDLL 'kernel32', handle .. at ...>
>>> print(cdll.msvcrt)      
<CDLL 'msvcrt', handle .. at ...>
>>> libc = cdll.msvcrt      
>>>
_

Windows menambahkan akhiran file

>>> c_int()
c_long(0)
>>> c_wchar_p("Hello, World")
c_wchar_p(140018365411392)
>>> c_ushort(-3)
c_ushort(65533)
>>>
_7 biasa secara otomatis

Catatan

Mengakses pustaka C standar melalui

>>> c_int()
c_long(0)
>>> c_wchar_p("Hello, World")
c_wchar_p(140018365411392)
>>> c_ushort(-3)
c_ushort(65533)
>>>
_8 akan menggunakan versi lama pustaka yang mungkin tidak kompatibel dengan versi yang digunakan oleh Python. Jika memungkinkan, gunakan fungsionalitas asli Python, atau impor dan gunakan modul
>>> c_int()
c_long(0)
>>> c_wchar_p("Hello, World")
c_wchar_p(140018365411392)
>>> c_ushort(-3)
c_ushort(65533)
>>>
6

Di Linux, diperlukan untuk menentukan nama file termasuk ekstensi untuk memuat pustaka, sehingga akses atribut tidak dapat digunakan untuk memuat pustaka. Metode

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
_00 dari pemuat dll harus digunakan, atau Anda harus memuat pustaka dengan membuat turunan CDLL dengan memanggil konstruktor

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>

Mengakses fungsi dari dll yang dimuat

Fungsi diakses sebagai atribut objek dll

>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>

Perhatikan bahwa sistem win32 dll seperti

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
01 dan
>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
02 sering mengekspor ANSI serta versi UNICODE dari suatu fungsi. Versi UNICODE diekspor dengan
>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
03 ditambahkan ke nama, sedangkan versi ANSI diekspor dengan
>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
04 ditambahkan ke nama. Fungsi win32
>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
_05, yang mengembalikan pegangan modul untuk nama modul tertentu, memiliki prototipe C berikut, dan makro digunakan untuk mengekspos salah satunya sebagai
>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
05 tergantung pada apakah UNICODE didefinisikan atau tidak

/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);

windll tidak mencoba untuk memilih salah satunya dengan sihir, Anda harus mengakses versi yang Anda butuhkan dengan menentukan

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
07 atau
>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
08 secara eksplisit, dan kemudian memanggilnya dengan objek byte atau string masing-masing

Terkadang, dll mengekspor fungsi dengan nama yang bukan pengidentifikasi Python yang valid, seperti

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
09. Dalam hal ini Anda harus menggunakan untuk mengambil fungsi

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>

Di Windows, beberapa fungsi ekspor dll bukan berdasarkan nama tetapi secara berurutan. Fungsi-fungsi ini dapat diakses dengan mengindeks objek dll dengan nomor urut

>>> cdll.kernel32[1]  
<_FuncPtr object at 0x...>
>>> cdll.kernel32[0]  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 310, in __getitem__
    func = _StdcallFuncPtr(name, self)
AttributeError: function ordinal 0 not found
>>>

Fungsi pemanggilan

Anda dapat memanggil fungsi-fungsi ini seperti callable Python lainnya. Contoh ini menggunakan fungsi

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
11, yang mengembalikan waktu sistem dalam hitungan detik sejak zaman Unix, dan fungsi
>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
12, yang mengembalikan pegangan modul win32

Contoh ini memanggil kedua fungsi dengan pointer

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
13 (
>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
14 harus digunakan sebagai pointer
>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
13)

>>> print(libc.time(None))  
1150640792
>>> print(hex(windll.kernel32.GetModuleHandleA(None)))  
0x1d000000
>>>

dimunculkan saat Anda memanggil fungsi

>>> c_int()
c_long(0)
>>> c_wchar_p("Hello, World")
c_wchar_p(140018365411392)
>>> c_ushort(-3)
c_ushort(65533)
>>>
_0 dengan konvensi pemanggilan ________0______9, atau sebaliknya

>>> cdll.kernel32.GetModuleHandleA(None)  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Procedure probably called with not enough arguments (4 bytes missing)
>>>

>>> windll.msvcrt.printf(b"spam")  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Procedure probably called with too many arguments (4 bytes in excess)
>>>

Untuk mengetahui konvensi pemanggilan yang benar, Anda harus melihat file header C atau dokumentasi untuk fungsi yang ingin Anda panggil

Di Windows, menggunakan penanganan pengecualian terstruktur win32 untuk mencegah crash akibat kesalahan perlindungan umum saat fungsi dipanggil dengan nilai argumen yang tidak valid

>>> windll.kernel32.GetModuleHandleA(32)  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: exception: access violation reading 0x00000020
>>>

Namun, ada cukup banyak cara untuk membuat crash Python dengan , jadi Anda tetap harus berhati-hati. Modul ini dapat membantu dalam men-debug crash (mis. g. dari kesalahan segmentasi yang dihasilkan oleh panggilan perpustakaan C yang salah)

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
14, bilangan bulat, objek byte, dan string (unicode) adalah satu-satunya objek Python asli yang dapat langsung digunakan sebagai parameter dalam pemanggilan fungsi ini.
>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
14 diteruskan sebagai penunjuk C
>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
13, objek byte dan string diteruskan sebagai penunjuk ke blok memori yang berisi datanya ( char* or wchar_t*). Python integers are passed as the platforms default C int default platform, nilainya disamarkan agar sesuai dengan tipe C.

Sebelum kita melanjutkan pemanggilan fungsi dengan tipe parameter lain, kita harus mempelajari lebih lanjut tentang tipe data

Tipe data dasar

mendefinisikan sejumlah tipe data kompatibel C primitif

tipe ctypes

tipe C

Jenis ular piton

_Bool

minuman keras (1)

arang

objek byte 1 karakter

wchar_t

string 1 karakter

arang

int

tidak ditandatangani char

int

pendek

int

tidak ditandatangani pendek

int

int

int

tidak ditandatangani int

int

panjang

int

tidak bertanda tangan panjang

int

__int64 atau panjang panjang

int

tidak bertanda tangan __int64 atau tidak bertanda tangan panjang long

int

size_t

int

ssize_t atau

int

mengambang

mengambang

dobel

mengambang

panjang ganda

mengambang

char* (NUL dihentikan)

objek byte atau

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
_14

wchar_t* (NUL dihentikan)

string atau

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
_14

batal*

int atau

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
_14

  1. Konstruktor menerima objek apa pun dengan nilai kebenaran

Semua jenis ini dapat dibuat dengan memanggilnya dengan penginisialisasi opsional dari jenis dan nilai yang benar

>>> c_int()
c_long(0)
>>> c_wchar_p("Hello, World")
c_wchar_p(140018365411392)
>>> c_ushort(-3)
c_ushort(65533)
>>>

Karena tipe ini bisa berubah, nilainya juga bisa diubah setelahnya

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
_0

Menetapkan nilai baru ke instance pointer types , , dan mengubah lokasi memori yang mereka tunjuk, bukan konten blok memori (tentu saja tidak, karena objek byte Python tidak dapat diubah)

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
_1

Namun, Anda harus berhati-hati agar tidak meneruskannya ke fungsi yang mengharapkan petunjuk ke memori yang dapat diubah. Jika Anda memerlukan blok memori yang dapat diubah, ctypes memiliki fungsi yang membuatnya dengan berbagai cara. Isi blok memori saat ini dapat diakses (atau diubah) dengan properti

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
55;

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
_2

Fungsi menggantikan fungsi

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
58 lama (yang masih tersedia sebagai alias). Untuk membuat blok memori yang dapat diubah yang berisi karakter unicode tipe C wchar_t , gunakan fungsi.

Memanggil fungsi, lanjutan

Perhatikan bahwa printf mencetak ke saluran output standar yang sebenarnya, bukan ke , jadi contoh ini hanya akan berfungsi di prompt konsol, bukan dari dalam IDLE atau PythonWin

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
_3

Seperti yang telah disebutkan sebelumnya, semua tipe Python kecuali objek integer, string, dan byte harus dibungkus dengan tipe yang sesuai, sehingga dapat dikonversi ke tipe data C yang diperlukan.

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
_4

Memanggil fungsi variadik

Pada banyak platform, pemanggilan fungsi variadic melalui ctypes sama persis dengan pemanggilan fungsi dengan jumlah parameter yang tetap. Pada beberapa platform, khususnya ARM64 untuk Platform Apple, konvensi pemanggilan untuk fungsi variadic berbeda dari fungsi biasa

Pada platform tersebut, diperlukan untuk menentukan atribut argtypes untuk argumen fungsi reguler, non-variadik

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
_5

Karena menentukan atribut tidak menghambat portabilitas, disarankan untuk selalu menentukan

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
62 untuk semua fungsi variadik

Memanggil fungsi dengan tipe data kustom Anda sendiri

Anda juga dapat menyesuaikan konversi argumen untuk mengizinkan instance kelas Anda sendiri digunakan sebagai argumen fungsi. mencari atribut

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
_65 dan menggunakan this sebagai argumen fungsi. Tentu saja, itu harus berupa bilangan bulat, string, atau byte

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
_6

Jika Anda tidak ingin menyimpan data instance dalam variabel instance

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
65, Anda dapat menentukan a which membuat atribut tersedia berdasarkan permintaan

Menentukan jenis argumen yang diperlukan (prototipe fungsi)

Dimungkinkan untuk menentukan jenis argumen yang diperlukan dari fungsi yang diekspor dari DLL dengan menyetel atribut

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
62

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
62 must be a sequence of C data types (the
>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
70 function is probably not a good example here, because it takes a variable number and different types of parameters depending on the format string, on the other hand this is quite handy to experiment with this feature)

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
7

Specifying a format protects against incompatible argument types (just as a prototype for a C function), and tries to convert the arguments to valid types

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
8

Jika Anda telah menentukan kelas Anda sendiri yang Anda berikan ke panggilan fungsi, Anda harus menerapkan metode kelas

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
71 agar mereka dapat menggunakannya dalam urutan
>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
62. Metode kelas
>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
_71 menerima objek Python yang diteruskan ke pemanggilan fungsi, ia harus melakukan pemeriksaan ketik atau apa pun yang diperlukan untuk memastikan objek ini dapat diterima, dan kemudian mengembalikan objek itu sendiri, atribut
>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
65, atau apa pun yang ingin Anda berikan sebagai . Sekali lagi, hasilnya harus berupa integer, string, byte, instance, atau objek dengan atribut
>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
65

Jenis pengembalian

Secara default fungsi diasumsikan mengembalikan tipe C int . Jenis pengembalian lainnya dapat ditentukan dengan menyetel atribut ________10______77 dari objek fungsi.

Here is a more advanced example, it uses the

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
78 function, which expects a string pointer and a char, and returns a pointer to a string

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
9

If you want to avoid the

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
79 calls above, you can set the
>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
62 attribute, and the second argument will be converted from a single character Python bytes object into a C char

>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
0

You can also use a callable Python object (a function or a class for example) as the

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
77 attribute, if the foreign function returns an integer. The callable will be called with the integer the C function returns, and the result of this call will be used as the result of your function call. This is useful to check for error return values and automatically raise an exception

>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
1

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
82 is a function which will call Windows
>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
83 api to get the string representation of an error code, and returns an exception.
>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
82 takes an optional error code parameter, if no one is used, it calls to retrieve it

Please note that a much more powerful error checking mechanism is available through the

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
86 attribute; see the reference manual for details

Passing pointers (or. passing parameters by reference)

Sometimes a C api function expects a pointer to a data type as parameter, probably to write into the corresponding location, or if the data is too large to be passed by value. This is also known as passing parameters by reference

exports the function which is used to pass parameters by reference. The same effect can be achieved with the function, although does a lot more work since it constructs a real pointer object, so it is faster to use if you don’t need the pointer object in Python itself

>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
2

Structures and unions

Structures and unions must derive from the and base classes which are defined in the module. Each subclass must define a

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
95 attribute.
>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
95 must be a list of 2-tuples, containing a field name and a field type

The field type must be a type like , or any other derived type. structure, union, array, pointer

Here is a simple example of a POINT structure, which contains two integers named x and y, and also shows how to initialize a structure in the constructor

>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
3

You can, however, build much more complicated structures. A structure can itself contain other structures by using a structure as a field type

Here is a RECT structure which contains two POINTs named upperleft and lowerright

>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
4

Nested structures can also be initialized in the constructor in several ways

>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
5

Field s can be retrieved from the class, they are useful for debugging because they can provide useful information

>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
6

Warning

does not support passing unions or structures with bit-fields to functions by value. While this may work on 32-bit x86, it’s not guaranteed by the library to work in the general case. Unions and structures with bit-fields should always be passed to functions by pointer

Structure/union alignment and byte order

By default, Structure and Union fields are aligned in the same way the C compiler does it. It is possible to override this behavior by specifying a

>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
01 class attribute in the subclass definition. This must be set to a positive integer and specifies the maximum alignment for the fields. This is what
>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
02 also does in MSVC

uses the native byte order for Structures and Unions. To build structures with non-native byte order, you can use one of the , , , and base classes. These classes cannot contain pointer fields

Bit fields in structures and unions

It is possible to create structures and unions containing bit fields. Bit fields are only possible for integer fields, the bit width is specified as the third item in the

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
95 tuples

>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
7

Arrays

Arrays are sequences, containing a fixed number of instances of the same type

The recommended way to create array types is by multiplying a data type with a positive integer

>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
8

Here is an example of a somewhat artificial data type, a structure containing 4 POINTs among other stuff

>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
9

Instances are created in the usual way, by calling the class

/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
0

The above code print a series of

>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
09 lines, because the array contents is initialized to zeros

Initializers of the correct type can also be specified

/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
1

Pointers

Pointer instances are created by calling the function on a type

/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
_2

Pointer instances have a attribute which returns the object to which the pointer points, the

>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
13 object above

/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
3

Note that does not have OOR (original object return), it constructs a new, equivalent object each time you retrieve an attribute

/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
4

Assigning another instance to the pointer’s contents attribute would cause the pointer to point to the memory location where this is stored

/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
5

Pointer instances can also be indexed with integers

/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
6

Assigning to an integer index changes the pointed to value

/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
7

It is also possible to use indexes different from 0, but you must know what you’re doing, just as in C. You can access or change arbitrary memory locations. Umumnya Anda hanya menggunakan fitur ini jika Anda menerima pointer dari fungsi C, dan Anda tahu bahwa pointer sebenarnya menunjuk ke array, bukan satu item

Di belakang layar, fungsi melakukan lebih dari sekadar membuat instance pointer, ia harus membuat tipe pointer terlebih dahulu. Ini dilakukan dengan fungsi, yang menerima tipe apapun, dan mengembalikan tipe baru

/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
_8

Memanggil tipe pointer tanpa argumen membuat

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
13 pointer.
>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
_13 pointer memiliki
>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
21 nilai boolean

/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
_9

memeriksa

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
13 ketika dereferencing pointer (tetapi dereferencing tidak valid non-
>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
13 pointer akan crash Python)

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
0

Ketik konversi

Biasanya, ctypes melakukan pemeriksaan tipe yang ketat. Ini berarti, jika Anda memiliki

>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
_25 di
>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
62 daftar fungsi atau sebagai tipe bidang anggota dalam definisi struktur, hanya instance dari tipe yang persis sama yang diterima. Ada beberapa pengecualian untuk aturan ini, di mana ctypes menerima objek lain. Misalnya, Anda dapat meneruskan instance array yang kompatibel alih-alih tipe pointer. Jadi, untuk
>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
_25, ctypes menerima array c_int

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
_1

Selain itu, jika argumen fungsi dinyatakan secara eksplisit sebagai tipe penunjuk (seperti

>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
25) di
>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
62, objek bertipe runcing (
>>> windll.kernel32.GetModuleHandleA(32)  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: exception: access violation reading 0x00000020
>>>
3 dalam hal ini) dapat diteruskan ke fungsi. ctypes akan menerapkan konversi yang diperlukan dalam hal ini secara otomatis

Untuk menyetel bidang jenis POINTER ke

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
13, Anda dapat menetapkan
>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
14

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
_2

Terkadang Anda memiliki contoh tipe yang tidak kompatibel. Di C, Anda dapat memasukkan satu tipe ke tipe lain. menyediakan fungsi yang dapat digunakan dengan cara yang sama. Struktur

>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
_36 yang didefinisikan di atas menerima
>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
25 pointer atau array untuk bidang
>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
39, tetapi bukan instance dari tipe lain

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
_3

Untuk kasus ini, fungsinya berguna

Fungsi ini dapat digunakan untuk mentransmisikan instance ctypes ke dalam pointer ke tipe data ctypes yang berbeda. mengambil dua parameter, objek ctypes yang sedang atau dapat dikonversi menjadi semacam pointer, dan tipe pointer ctypes. Ia mengembalikan instance dari argumen kedua, yang mereferensikan blok memori yang sama dengan argumen pertama

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
_4

Jadi, dapat digunakan untuk menetapkan bidang

>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
39 dari
>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
36 struktur

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
_5

Jenis Tidak Lengkap

Tipe Tidak Lengkap adalah struktur, gabungan, atau larik yang anggotanya belum ditentukan. Di C, mereka ditentukan oleh deklarasi maju, yang ditentukan nanti

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
_6

Terjemahan langsung ke dalam kode ctypes adalah ini, tetapi tidak berhasil

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
_7

karena

>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
_46 baru tidak tersedia dalam pernyataan kelas itu sendiri. Di , kita dapat mendefinisikan kelas
>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
_48 dan mengatur atribut
>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
95 nanti, setelah pernyataan kelas

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
_8

Mari kita coba. Kami membuat dua contoh

>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
48, dan membiarkan mereka saling menunjuk, dan akhirnya mengikuti rantai penunjuk beberapa kali

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
_9

Fungsi panggilan balik

memungkinkan membuat pointer fungsi callable C dari callable Python. Ini terkadang disebut fungsi panggilan balik

Pertama, Anda harus membuat kelas untuk fungsi callback. Kelas mengetahui konvensi pemanggilan, tipe pengembalian, dan jumlah serta tipe argumen yang akan diterima fungsi ini

Fungsi pabrik membuat tipe untuk fungsi callback menggunakan konvensi pemanggilan

>>> windll.kernel32.GetModuleHandleA(32)  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: exception: access violation reading 0x00000020
>>>
9. Di Windows, fungsi pabrik membuat tipe untuk fungsi callback menggunakan konvensi pemanggilan
>>> c_int()
c_long(0)
>>> c_wchar_p("Hello, World")
c_wchar_p(140018365411392)
>>> c_ushort(-3)
c_ushort(65533)
>>>
0

Kedua fungsi pabrik ini dipanggil dengan tipe hasil sebagai argumen pertama, dan fungsi callback tipe argumen yang diharapkan sebagai argumen yang tersisa

Saya akan menyajikan contoh di sini yang menggunakan fungsi

>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
56 perpustakaan C standar, yang digunakan untuk mengurutkan item dengan bantuan fungsi callback.
>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
56 akan digunakan untuk mengurutkan array bilangan bulat

>>> cdll.kernel32[1]  
<_FuncPtr object at 0x...>
>>> cdll.kernel32[0]  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 310, in __getitem__
    func = _StdcallFuncPtr(name, self)
AttributeError: function ordinal 0 not found
>>>
0

>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
56 harus dipanggil dengan penunjuk ke data yang akan diurutkan, jumlah item dalam larik data, ukuran satu item, dan penunjuk ke fungsi perbandingan, panggilan balik. Callback kemudian akan dipanggil dengan dua pointer ke item, dan harus mengembalikan bilangan bulat negatif jika item pertama lebih kecil dari yang kedua, nol jika sama, dan bilangan bulat positif jika tidak

Jadi fungsi panggilan balik kami menerima pointer ke bilangan bulat, dan harus mengembalikan bilangan bulat. Pertama kita membuat

>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
_59 untuk fungsi callback

>>> cdll.kernel32[1]  
<_FuncPtr object at 0x...>
>>> cdll.kernel32[0]  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 310, in __getitem__
    func = _StdcallFuncPtr(name, self)
AttributeError: function ordinal 0 not found
>>>
1

Untuk memulai, berikut adalah callback sederhana yang menunjukkan nilai yang diteruskan

>>> cdll.kernel32[1]  
<_FuncPtr object at 0x...>
>>> cdll.kernel32[0]  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 310, in __getitem__
    func = _StdcallFuncPtr(name, self)
AttributeError: function ordinal 0 not found
>>>
2

Hasil

>>> cdll.kernel32[1]  
<_FuncPtr object at 0x...>
>>> cdll.kernel32[0]  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 310, in __getitem__
    func = _StdcallFuncPtr(name, self)
AttributeError: function ordinal 0 not found
>>>
3

Sekarang kita benar-benar dapat membandingkan dua item dan mengembalikan hasil yang bermanfaat

>>> cdll.kernel32[1]  
<_FuncPtr object at 0x...>
>>> cdll.kernel32[0]  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 310, in __getitem__
    func = _StdcallFuncPtr(name, self)
AttributeError: function ordinal 0 not found
>>>
4

Karena kita dapat dengan mudah memeriksa, array kita sudah diurutkan sekarang

>>> cdll.kernel32[1]  
<_FuncPtr object at 0x...>
>>> cdll.kernel32[0]  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 310, in __getitem__
    func = _StdcallFuncPtr(name, self)
AttributeError: function ordinal 0 not found
>>>
5

Fungsi pabrik dapat digunakan sebagai pabrik penghias, jadi sebaiknya kita tulis saja

>>> cdll.kernel32[1]  
<_FuncPtr object at 0x...>
>>> cdll.kernel32[0]  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 310, in __getitem__
    func = _StdcallFuncPtr(name, self)
AttributeError: function ordinal 0 not found
>>>
6

Catatan

Pastikan Anda menyimpan referensi ke objek selama digunakan dari kode C. tidak, dan jika tidak, mereka mungkin mengumpulkan sampah, merusak program Anda saat panggilan balik dilakukan

Juga, perhatikan bahwa jika fungsi panggilan balik dipanggil di utas yang dibuat di luar kendali Python (mis. g. oleh kode asing yang memanggil panggilan balik), ctypes membuat utas Python dummy baru pada setiap doa. Perilaku ini benar untuk sebagian besar tujuan, tetapi itu berarti bahwa nilai yang disimpan dengan tidak akan bertahan di callback yang berbeda, meskipun panggilan tersebut dibuat dari utas C yang sama

Mengakses nilai yang diekspor dari dll

Beberapa pustaka bersama tidak hanya mengekspor fungsi, tetapi juga mengekspor variabel. Contoh di pustaka Python itu sendiri adalah , bilangan bulat yang disetel ke 0, 1, atau 2, tergantung pada tanda atau yang diberikan saat startup

dapat mengakses nilai seperti ini dengan metode kelas ________12______67 dari tipe tersebut. pythonapi adalah simbol standar yang memberikan akses ke api Python C

>>> cdll.kernel32[1]  
<_FuncPtr object at 0x...>
>>> cdll.kernel32[0]  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 310, in __getitem__
    func = _StdcallFuncPtr(name, self)
AttributeError: function ordinal 0 not found
>>>
7

Jika juru bahasa dimulai dengan , sampel akan dicetak

>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
69, atau
>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
70 jika ditentukan

Contoh tambahan yang juga mendemonstrasikan penggunaan pointer mengakses pointer yang diekspor oleh Python

Mengutip dokumen untuk nilai itu

Pointer ini diinisialisasi untuk menunjuk ke array catatan, diakhiri oleh satu yang anggotanya semuanya

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
13 atau nol. Saat modul yang dibekukan diimpor, modul tersebut dicari di tabel ini. Kode pihak ketiga dapat memainkan trik dengan ini untuk menyediakan kumpulan modul beku yang dibuat secara dinamis

Jadi memanipulasi penunjuk ini bahkan terbukti bermanfaat. Untuk membatasi ukuran contoh, kami hanya menunjukkan bagaimana tabel ini dapat dibaca

>>> cdll.kernel32[1]  
<_FuncPtr object at 0x...>
>>> cdll.kernel32[0]  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 310, in __getitem__
    func = _StdcallFuncPtr(name, self)
AttributeError: function ordinal 0 not found
>>>
8

Kita telah menentukan tipe datanya, sehingga kita bisa mengarahkan pointer ke tabel

>>> cdll.kernel32[1]  
<_FuncPtr object at 0x...>
>>> cdll.kernel32[0]  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 310, in __getitem__
    func = _StdcallFuncPtr(name, self)
AttributeError: function ordinal 0 not found
>>>
_9

Karena

>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
_77 adalah
>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
78 ke array
>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
79 record, kita dapat mengulanginya, tetapi kita hanya perlu memastikan bahwa loop kita berakhir, karena pointer tidak memiliki ukuran. Cepat atau lambat itu mungkin akan macet dengan pelanggaran akses atau apa pun, jadi lebih baik untuk keluar dari loop saat kita menekan entri
>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
13

>>> print(libc.time(None))  
1150640792
>>> print(hex(windll.kernel32.GetModuleHandleA(None)))  
0x1d000000
>>>
0

Fakta bahwa Python standar memiliki modul beku dan paket beku (ditunjukkan dengan anggota negatif

>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
81) tidak diketahui, ini hanya digunakan untuk pengujian. Cobalah dengan
>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
_82 misalnya

Kejutan

Ada beberapa sisi di mana Anda mungkin mengharapkan sesuatu selain dari apa yang sebenarnya terjadi

Perhatikan contoh berikut

>>> print(libc.time(None))  
1150640792
>>> print(hex(windll.kernel32.GetModuleHandleA(None)))  
0x1d000000
>>>
1

Hm. Kami tentu mengharapkan pernyataan terakhir untuk mencetak ________12______84. Apa yang terjadi?

>>> print(libc.time(None))  
1150640792
>>> print(hex(windll.kernel32.GetModuleHandleA(None)))  
0x1d000000
>>>
2

Perhatikan bahwa

>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
_86 dan
>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
87 adalah objek yang masih menggunakan buffer internal dari objek
>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
88 di atas. Jadi mengeksekusi
>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
_89 menyalin isi buffer dari
>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
86 ke buffer
>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
88. Ini, pada gilirannya, mengubah isi ________12______87. Jadi, tugas terakhir
>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
_93, tidak memiliki efek yang diharapkan

Perlu diingat bahwa mengambil sub-objek dari Structure, Unions, dan Arrays tidak menyalin sub-objek, melainkan mengambil objek pembungkus yang mengakses buffer dasar objek root

Another example that may behave differently from what one would expect is this

>>> print(libc.time(None))  
1150640792
>>> print(hex(windll.kernel32.GetModuleHandleA(None)))  
0x1d000000
>>>
3

Catatan

Objects instantiated from can only have their value set to bytes or integers

Mengapa mencetak

>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
21? . Menyimpan objek Python di blok memori tidak menyimpan objek itu sendiri, melainkan
>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
12 objek disimpan. Mengakses konten lagi membuat objek Python baru setiap kali

Tipe data berukuran variabel

menyediakan beberapa dukungan untuk array dan struktur berukuran variabel

The function can be used to resize the memory buffer of an existing ctypes object. Fungsi mengambil objek sebagai argumen pertama, dan ukuran yang diminta dalam byte sebagai argumen kedua. Blok memori tidak dapat dibuat lebih kecil dari blok memori alami yang ditentukan oleh tipe objek, a dinaikkan jika ini dicoba

>>> print(libc.time(None))  
1150640792
>>> print(hex(windll.kernel32.GetModuleHandleA(None)))  
0x1d000000
>>>
4

Ini bagus dan bagus, tetapi bagaimana cara mengakses elemen tambahan yang terkandung dalam larik ini?

>>> print(libc.time(None))  
1150640792
>>> print(hex(windll.kernel32.GetModuleHandleA(None)))  
0x1d000000
>>>
5

Cara lain untuk menggunakan tipe data berukuran variabel adalah dengan menggunakan sifat dinamis Python, dan (kembali) mendefinisikan tipe data setelah ukuran yang diperlukan sudah diketahui, berdasarkan kasus per kasus

referensi ctypes

Menemukan perpustakaan bersama

Saat memprogram dalam bahasa yang dikompilasi, pustaka bersama diakses saat mengompilasi/menautkan program, dan saat program dijalankan

Tujuan dari fungsi

/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
_01 adalah untuk menemukan perpustakaan dengan cara yang mirip dengan apa yang dilakukan oleh compiler atau runtime loader (pada platform dengan beberapa versi perpustakaan bersama, yang terbaru harus dimuat), sedangkan pemuat perpustakaan ctypes bertindak seperti ketika

Modul

/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
_02 menyediakan fungsi yang dapat membantu menentukan pustaka yang akan dimuat

ctypes. utilitas. find_library(nama)

Cobalah untuk menemukan perpustakaan dan kembalikan nama path. name adalah nama perpustakaan tanpa awalan seperti lib, akhiran seperti

/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
03,
/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
04 atau nomor versi (ini adalah formulir yang digunakan untuk opsi posix linker
/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
05). Jika tidak ada pustaka yang dapat ditemukan, kembalikan
>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
14

The exact functionality is system dependent

Di Linux,

/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
_01 mencoba menjalankan program eksternal (
/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
08,
/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
09,
/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
10 dan
/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
11) untuk menemukan file perpustakaan. Ini mengembalikan nama file dari file perpustakaan

Berubah di versi 3. 6. Di Linux, nilai variabel lingkungan

/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
12 digunakan saat mencari perpustakaan, jika perpustakaan tidak dapat ditemukan dengan cara lain.

Berikut beberapa contohnya

>>> print(libc.time(None))  
1150640792
>>> print(hex(windll.kernel32.GetModuleHandleA(None)))  
0x1d000000
>>>
6

Di macOS,

/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
01 mencoba beberapa skema penamaan dan jalur yang telah ditentukan sebelumnya untuk menemukan perpustakaan, dan mengembalikan nama jalur lengkap jika berhasil

>>> print(libc.time(None))  
1150640792
>>> print(hex(windll.kernel32.GetModuleHandleA(None)))  
0x1d000000
>>>
7

Di Windows,

/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
01 mencari di sepanjang jalur pencarian sistem, dan mengembalikan nama path lengkap, tetapi karena tidak ada skema penamaan yang telah ditentukan, panggilan seperti
/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
15 akan gagal dan mengembalikan
>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
14

Jika membungkus perpustakaan bersama dengan , mungkin lebih baik untuk menentukan nama perpustakaan bersama pada waktu pengembangan, dan meng-hardcode-nya ke dalam modul pembungkus daripada menggunakan

/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
01 untuk menemukan perpustakaan pada waktu proses

Memuat pustaka bersama

Ada beberapa cara untuk memuat pustaka bersama ke dalam proses Python. Salah satu caranya adalah dengan menginstansiasi salah satu kelas berikut

kelas tipe. CDLL(nama , mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False, winmode=None)

Instance kelas ini mewakili pustaka bersama yang dimuat. Functions in these libraries use the standard C calling convention, and are assumed to return int .

Di Windows, pembuatan instance mungkin gagal meskipun nama DLL ada. Ketika DLL dependen dari DLL yang dimuat tidak ditemukan, kesalahan muncul dengan pesan "[WinError 126] Modul yang ditentukan tidak dapat ditemukan". Pesan galat ini tidak berisi nama DLL yang hilang karena Windows API tidak mengembalikan informasi ini membuat galat ini sulit didiagnosis. Untuk mengatasi kesalahan ini dan menentukan DLL mana yang tidak ditemukan, Anda perlu menemukan daftar DLL dependen dan menentukan mana yang tidak ditemukan menggunakan alat debugging dan penelusuran Windows

Lihat juga

Alat Microsoft DUMPBIN – Alat untuk menemukan tanggungan DLL

kelas tipe. OleDLL(nama , mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False, winmode=None)

Jendela saja. Instance kelas ini mewakili pustaka bersama yang dimuat, fungsi dalam pustaka ini menggunakan konvensi pemanggilan

>>> c_int()
c_long(0)
>>> c_wchar_p("Hello, World")
c_wchar_p(140018365411392)
>>> c_ushort(-3)
c_ushort(65533)
>>>
0, dan dianggap mengembalikan kode khusus windows. values contain information specifying whether the function call failed or succeeded, together with additional error code. Jika nilai pengembalian menandakan kegagalan, an secara otomatis dinaikkan

Berubah di versi 3. 3. used to be raised.

kelas tipe. WinDLL(nama , mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False, winmode=None)

Hanya Windows. Instance kelas ini merepresentasikan pustaka bersama yang dimuat, fungsi dalam pustaka ini menggunakan konvensi pemanggilan

>>> c_int()
c_long(0)
>>> c_wchar_p("Hello, World")
c_wchar_p(140018365411392)
>>> c_ushort(-3)
c_ushort(65533)
>>>
0, dan diasumsikan mengembalikan int secara default.

Python dirilis sebelum memanggil fungsi apa pun yang diekspor oleh pustaka ini, dan diperoleh kembali setelahnya

kelas tipe. PyDLL(nama , mode=DEFAULT_MODE, handle=None)

Instances of this class behave like instances, except that the Python GIL is not released during the function call, and after the function execution the Python error flag is checked. Jika bendera kesalahan disetel, pengecualian Python dimunculkan

Jadi, ini hanya berguna untuk memanggil fungsi Python C api secara langsung

Semua class ini dapat dibuat instance-nya dengan memanggilnya dengan setidaknya satu argumen, nama path dari shared library. Jika Anda memiliki pegangan yang ada untuk perpustakaan bersama yang sudah dimuat, itu dapat diteruskan sebagai parameter bernama

/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
28, jika tidak, platform yang mendasari
/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
29 atau
/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
30 fungsi digunakan untuk memuat perpustakaan ke dalam proses, dan untuk mendapatkan pegangan untuk itu

Parameter mode dapat digunakan untuk menentukan bagaimana perpustakaan dimuat. Untuk detailnya, lihat dlopen(3) halaman manual. Di Windows, mode diabaikan. Pada sistem posix, RTLD_NOW selalu ditambahkan, dan tidak dapat dikonfigurasi

Parameter use_errno, jika disetel ke true, mengaktifkan mekanisme ctypes yang memungkinkan akses ke nomor kesalahan sistem dengan cara yang aman. menyimpan salinan thread-local dari variabel sistem;

Fungsi mengembalikan nilai salinan pribadi ctypes, dan fungsi mengubah salinan pribadi ctypes ke nilai baru dan mengembalikan nilai sebelumnya

Parameter use_last_error, jika disetel ke true, mengaktifkan mekanisme yang sama untuk kode kesalahan Windows yang dikelola oleh dan

/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
39 fungsi Windows API;

Parameter winmode digunakan pada Windows untuk menentukan bagaimana perpustakaan dimuat (karena mode diabaikan). Dibutuhkan nilai apa pun yang valid untuk parameter bendera Win32 API

/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
42. Jika dihilangkan, standarnya adalah menggunakan tanda yang menghasilkan pemuatan DLL paling aman untuk menghindari masalah seperti pembajakan DLL. Melewati jalur lengkap ke DLL adalah cara teraman untuk memastikan perpustakaan dan dependensi yang benar dimuat

Berubah di versi 3. 8. Menambahkan parameter winmode.

ctypes. RTLD_GLOBAL

Tandai untuk digunakan sebagai parameter mode. Pada platform di mana bendera ini tidak tersedia, itu didefinisikan sebagai bilangan bulat nol

ctypes. RTLD_LOCAL

Tandai untuk digunakan sebagai parameter mode. Pada platform yang tidak tersedia, ini sama dengan RTLD_GLOBAL

ctypes. DEFAULT_MODE

Mode default yang digunakan untuk memuat pustaka bersama. Di OSX 10. 3, ini adalah RTLD_GLOBAL, selain itu sama dengan RTLD_LOCAL

Instance dari kelas-kelas ini tidak memiliki metode publik. Fungsi yang diekspor oleh pustaka bersama dapat diakses sebagai atribut atau indeks. Harap perhatikan bahwa mengakses fungsi melalui atribut menyimpan hasil dan karena itu mengaksesnya berulang kali mengembalikan objek yang sama setiap saat. Di sisi lain, mengaksesnya melalui indeks mengembalikan objek baru setiap saat

>>> print(libc.time(None))  
1150640792
>>> print(hex(windll.kernel32.GetModuleHandleA(None)))  
0x1d000000
>>>
8

The following public attributes are available, their name starts with an underscore to not clash with exported function names

PyDLL. _pegangan

Pegangan sistem yang digunakan untuk mengakses perpustakaan

PyDLL. _nama

Nama perpustakaan diteruskan dalam konstruktor

Pustaka bersama juga dapat dimuat dengan menggunakan salah satu objek prefabrikasi, yang merupakan turunan dari kelas, baik dengan memanggil metode

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
00, atau dengan mengambil pustaka sebagai atribut dari turunan pemuat

kelas tipe. LibraryLoader(jenis dll)

Class which loads shared libraries. dlltype should be one of the , , , or types

/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
_49 memiliki perilaku khusus. Ini memungkinkan memuat pustaka bersama dengan mengaksesnya sebagai atribut dari instance pemuat pustaka. Hasilnya di-cache, sehingga akses atribut yang berulang mengembalikan perpustakaan yang sama setiap saat

LoadLibrary(nama)

Muat pustaka bersama ke dalam proses dan kembalikan. Metode ini selalu mengembalikan instance perpustakaan yang baru

Pemuat perpustakaan prefabrikasi ini tersedia

ctypes. cdll

Membuat instance

ctypes. windll

Jendela saja. Creates instances

ctypes. oledll

Jendela saja. Creates instances

ctypes. pydll

Membuat instance

Untuk mengakses api C Python secara langsung, tersedia objek pustaka bersama Python siap pakai

ctypes. pythonapi

Contoh yang memperlihatkan fungsi Python C API sebagai atribut. Perhatikan bahwa semua fungsi ini diasumsikan mengembalikan C int , yang tentu saja tidak selalu benar, jadi Anda harus menetapkan atribut

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
77 yang benar untuk digunakan .

Memuat pustaka melalui salah satu objek ini memunculkan

/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
56 dengan argumen string
/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
57, nama yang digunakan untuk memuat pustaka

Mengakses fungsi pada pustaka yang dimuat memunculkan peristiwa audit

/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
58 dengan argumen
/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
59 (objek pustaka) dan
/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
57 (nama simbol sebagai string atau bilangan bulat)

Dalam kasus ketika hanya pegangan perpustakaan yang tersedia daripada objek, mengakses fungsi memunculkan acara audit

/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
61 dengan argumen
/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
28 (pegangan perpustakaan mentah) dan
/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
57

Fungsi asing

Seperti yang dijelaskan di bagian sebelumnya, fungsi asing dapat diakses sebagai atribut pustaka bersama yang dimuat. Objek fungsi yang dibuat dengan cara ini secara default menerima sejumlah argumen, menerima instance data ctypes apa pun sebagai argumen, dan mengembalikan tipe hasil default yang ditentukan oleh pemuat pustaka. They are instances of a private class

kelas tipe. _FuncPtr

Kelas dasar untuk fungsi asing C yang dapat dipanggil

Instance dari fungsi asing juga merupakan tipe data yang kompatibel dengan C;

Perilaku ini dapat dikustomisasi dengan menetapkan atribut khusus dari objek fungsi asing

ketik ulang

Assign a ctypes type to specify the result type of the foreign function. Gunakan

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
14 untuk void , sebuah fungsi yang tidak mengembalikan apa pun.

Dimungkinkan untuk menetapkan objek Python yang dapat dipanggil yang bukan tipe ctypes, dalam hal ini fungsi diasumsikan mengembalikan C int, and the callable will be called with this integer, allowing further processing or error checking. Using this is deprecated, for more flexible post processing or error checking use a ctypes data type as and assign a callable to the attribute.

argtypes

Tetapkan tuple tipe ctypes untuk menentukan tipe argumen yang diterima fungsi. Fungsi yang menggunakan konvensi pemanggilan

>>> c_int()
c_long(0)
>>> c_wchar_p("Hello, World")
c_wchar_p(140018365411392)
>>> c_ushort(-3)
c_ushort(65533)
>>>
0 hanya dapat dipanggil dengan jumlah argumen yang sama dengan panjang tupel ini;

Ketika fungsi asing dipanggil, setiap argumen aktual diteruskan ke metode kelas

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
71 item dalam tuple, metode ini memungkinkan mengadaptasi argumen aktual ke objek yang diterima fungsi asing. Misalnya, item dalam tuple akan mengonversi string yang diteruskan sebagai argumen menjadi objek byte menggunakan aturan konversi ctypes

Baru. Sekarang dimungkinkan untuk meletakkan item dalam tipe arg yang bukan tipe ctype, tetapi setiap item harus memiliki metode

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
71 yang mengembalikan nilai yang dapat digunakan sebagai argumen (integer, string, contoh ctypes). Ini memungkinkan menentukan adaptor yang dapat mengadaptasi objek khusus sebagai parameter fungsi

periksa kesalahan

Tetapkan fungsi Python atau callable lainnya ke atribut ini. Callable akan dipanggil dengan tiga atau lebih argumen

dapat dipanggil(hasil , fungsi, arguments)

hasilnya adalah apa yang dikembalikan oleh fungsi asing, seperti yang ditentukan oleh atribut

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
77

func is the foreign function object itself, this allows reusing the same callable object to check or post process the results of several functions

argumen adalah tupel yang berisi parameter yang awalnya diteruskan ke pemanggilan fungsi, ini memungkinkan mengkhususkan perilaku pada argumen yang digunakan

Objek yang dikembalikan fungsi ini akan dikembalikan dari pemanggilan fungsi asing, tetapi juga dapat memeriksa nilai hasil dan memunculkan pengecualian jika pemanggilan fungsi asing gagal

pengecualian jenis. ArgumentError

Pengecualian ini muncul saat pemanggilan fungsi asing tidak dapat mengonversi salah satu argumen yang diteruskan

Di Windows, ketika panggilan fungsi asing menimbulkan pengecualian sistem (misalnya, karena pelanggaran akses), itu akan ditangkap dan diganti dengan pengecualian Python yang sesuai. Selanjutnya, acara audit

/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
_74 dengan argumen
/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
75 akan dimunculkan, memungkinkan kaitan audit untuk menggantikan pengecualian dengan pengecualiannya sendiri

Beberapa cara untuk memanggil panggilan fungsi asing dapat menimbulkan peristiwa audit

/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
76 dengan argumen
/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
77 dan
/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
78

Prototipe fungsi

Fungsi asing juga dapat dibuat dengan instantiating prototipe fungsi. Prototipe fungsi mirip dengan prototipe fungsi di C; . Fungsi pabrik harus dipanggil dengan tipe hasil yang diinginkan dan tipe argumen dari fungsi, dan dapat digunakan sebagai pabrik penghias, dan dengan demikian, diterapkan ke fungsi melalui sintaks ________19______79. Lihat untuk contoh

ctypes. CFUNCTYPE(ketik ulang , *argtypes, use_errno=False, use_last_error=False)

Prototipe fungsi yang dikembalikan membuat fungsi yang menggunakan konvensi pemanggilan C standar. Fungsi ini akan melepaskan GIL selama panggilan berlangsung. Jika use_errno disetel ke true, salinan pribadi ctypes dari variabel sistem ditukar dengan nilai sebenarnya sebelum dan sesudah panggilan;

ctypes. WINFUNCTYPE(ketik ulang , *argtypes, use_errno=False, use_last_error=False)

Jendela saja. Prototipe fungsi yang dikembalikan membuat fungsi yang menggunakan konvensi pemanggilan

>>> c_int()
c_long(0)
>>> c_wchar_p("Hello, World")
c_wchar_p(140018365411392)
>>> c_ushort(-3)
c_ushort(65533)
>>>
0. Fungsi ini akan melepaskan GIL selama panggilan berlangsung. use_errno dan use_last_error memiliki arti yang sama seperti di atas

ctypes. PYFUNCTYPE(ketik ulang , *argtypes)

Prototipe fungsi yang dikembalikan membuat fungsi yang menggunakan konvensi pemanggilan Python. Fungsi tidak akan melepaskan GIL selama panggilan

Prototipe fungsi yang dibuat oleh fungsi pabrik ini dapat dibuat dengan cara yang berbeda, bergantung pada jenis dan jumlah parameter dalam panggilan

prototipe(alamat)

Mengembalikan fungsi asing di alamat yang ditentukan yang harus bilangan bulat

prototipe(dapat dipanggil)

Buat fungsi callable C (fungsi callback) dari callable Python

prototipe(func_spec[ , paramflags])

Mengembalikan fungsi asing yang diekspor oleh pustaka bersama. func_spec harus berupa 2-tuple

/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
83. Item pertama adalah nama fungsi yang diekspor sebagai string, atau urutan fungsi yang diekspor sebagai bilangan bulat kecil. Item kedua adalah instance perpustakaan bersama

prototipe(vtbl_index , nama[, paramflags[, iid]])

Mengembalikan fungsi asing yang akan memanggil metode COM. vtbl_index adalah indeks ke dalam tabel fungsi virtual, bilangan bulat non-negatif kecil. nama adalah nama metode COM. iid adalah pointer opsional ke pengidentifikasi antarmuka yang digunakan dalam pelaporan kesalahan yang diperluas

COM methods use a special calling convention. They require a pointer to the COM interface as first argument, in addition to those parameters that are specified in the

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
62 tuple

Parameter paramflags opsional membuat pembungkus fungsi asing dengan lebih banyak fungsi daripada fitur yang dijelaskan di atas

paramflags must be a tuple of the same length as

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
62

Setiap item dalam tuple ini berisi informasi lebih lanjut tentang parameter, itu harus berupa tuple yang berisi satu, dua, atau tiga item

The first item is an integer containing a combination of direction flags for the parameter

1

Menentukan parameter input ke fungsi

2

Parameter keluaran. Fungsi asing mengisi nilai

4

Parameter input yang defaultnya adalah bilangan bulat nol

The optional second item is the parameter name as string. Jika ini ditentukan, fungsi asing dapat dipanggil dengan parameter bernama

Item ketiga opsional adalah nilai default untuk parameter ini

This example demonstrates how to wrap the Windows

/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
86 function so that it supports default parameters and named arguments. The C declaration from the windows header file is this

>>> print(libc.time(None))  
1150640792
>>> print(hex(windll.kernel32.GetModuleHandleA(None)))  
0x1d000000
>>>
9

Here is the wrapping with

>>> cdll.kernel32.GetModuleHandleA(None)  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Procedure probably called with not enough arguments (4 bytes missing)
>>>

>>> windll.msvcrt.printf(b"spam")  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Procedure probably called with too many arguments (4 bytes in excess)
>>>
0

Fungsi asing

/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
_88 sekarang dapat dipanggil dengan cara ini

>>> cdll.kernel32.GetModuleHandleA(None)  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Procedure probably called with not enough arguments (4 bytes missing)
>>>

>>> windll.msvcrt.printf(b"spam")  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Procedure probably called with too many arguments (4 bytes in excess)
>>>
_1

A second example demonstrates output parameters. The win32

/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
89 function retrieves the dimensions of a specified window by copying them into
/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
90 structure that the caller has to supply. Ini adalah deklarasi C

>>> cdll.kernel32.GetModuleHandleA(None)  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Procedure probably called with not enough arguments (4 bytes missing)
>>>

>>> windll.msvcrt.printf(b"spam")  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Procedure probably called with too many arguments (4 bytes in excess)
>>>
_2

Here is the wrapping with

>>> cdll.kernel32.GetModuleHandleA(None)  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Procedure probably called with not enough arguments (4 bytes missing)
>>>

>>> windll.msvcrt.printf(b"spam")  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Procedure probably called with too many arguments (4 bytes in excess)
>>>
_3

Functions with output parameters will automatically return the output parameter value if there is a single one, or a tuple containing the output parameter values when there are more than one, so the GetWindowRect function now returns a RECT instance, when called

Output parameters can be combined with the

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
86 protocol to do further output processing and error checking. Fungsi api win32
/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
_89 mengembalikan
/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
94 untuk menandakan keberhasilan atau kegagalan, sehingga fungsi ini dapat melakukan pemeriksaan kesalahan, dan memunculkan pengecualian saat panggilan api gagal

>>> cdll.kernel32.GetModuleHandleA(None)  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Procedure probably called with not enough arguments (4 bytes missing)
>>>

>>> windll.msvcrt.printf(b"spam")  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Procedure probably called with too many arguments (4 bytes in excess)
>>>
_4

If the

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
86 function returns the argument tuple it receives unchanged, continues the normal processing it does on the output parameters. Jika Anda ingin mengembalikan tuple koordinat jendela alih-alih instance
/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
90, Anda dapat mengambil bidang dalam fungsi dan mengembalikannya, pemrosesan normal tidak akan lagi dilakukan

>>> cdll.kernel32.GetModuleHandleA(None)  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Procedure probably called with not enough arguments (4 bytes missing)
>>>

>>> windll.msvcrt.printf(b"spam")  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Procedure probably called with too many arguments (4 bytes in excess)
>>>
5

Fungsi utilitas

ctypes. alamat(obj)

Mengembalikan alamat buffer memori sebagai bilangan bulat. obj must be an instance of a ctypes type

Raises an

/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
98 with argument
/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
99

ctypes. penyelarasan(obj_or_type)

Mengembalikan persyaratan penyelarasan dari tipe ctypes. obj_or_type must be a ctypes type or instance

ctypes. byref(obj[ , offset])

Returns a light-weight pointer to obj, which must be an instance of a ctypes type. offset default ke nol, dan harus bilangan bulat yang akan ditambahkan ke nilai pointer internal

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
00 corresponds to this C code

>>> cdll.kernel32.GetModuleHandleA(None)  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Procedure probably called with not enough arguments (4 bytes missing)
>>>

>>> windll.msvcrt.printf(b"spam")  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Procedure probably called with too many arguments (4 bytes in excess)
>>>
_6

The returned object can only be used as a foreign function call parameter. It behaves similar to

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
01, but the construction is a lot faster

ctypes. cast(obj , type)

This function is similar to the cast operator in C. It returns a new instance of type which points to the same memory block as obj. type harus berupa tipe pointer, dan obj harus berupa objek yang dapat diinterpretasikan sebagai pointer

ctypes. buat_string_buffer(init_or_size , ukuran=None)

Fungsi ini membuat buffer karakter yang bisa berubah. The returned object is a ctypes array of

init_or_size harus berupa bilangan bulat yang menentukan ukuran array, atau objek bytes yang akan digunakan untuk menginisialisasi item array

Jika objek bytes ditentukan sebagai argumen pertama, buffer dibuat satu item lebih besar dari panjangnya sehingga elemen terakhir dalam array adalah karakter terminasi NUL. Bilangan bulat dapat diteruskan sebagai argumen kedua yang memungkinkan menentukan ukuran array jika panjang byte tidak boleh digunakan

Memunculkan

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
03 dengan argumen
>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
04,
>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
81

ctypes. create_unicode_buffer(init_or_size , size=None)

Fungsi ini membuat buffer karakter unicode yang dapat diubah. Objek yang dikembalikan adalah array ctypes

init_or_size must be an integer which specifies the size of the array, or a string which will be used to initialize the array items

Jika string ditentukan sebagai argumen pertama, buffer dibuat satu item lebih besar dari panjang string sehingga elemen terakhir dalam array adalah karakter terminasi NUL. An integer can be passed as second argument which allows specifying the size of the array if the length of the string should not be used

Raises an

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
07 with arguments
>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
04,
>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
81

ctypes. DllCanUnloadNow()

Jendela saja. Fungsi ini adalah pengait yang memungkinkan penerapan server COM dalam proses dengan ctypes. Ini dipanggil dari fungsi DllCanUnloadNow yang diekspor dll ekstensi _ctypes

ctypes. DllGetClassObject()

Jendela saja. Fungsi ini adalah pengait yang memungkinkan penerapan server COM dalam proses dengan ctypes. Dipanggil dari fungsi DllGetClassObject yang diekspor oleh ekstensi

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
10

ctypes. utilitas. find_library(nama)

Cobalah untuk menemukan perpustakaan dan kembalikan nama path. name is the library name without any prefix like

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
11, suffix like
/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
03,
/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
04 or version number (this is the form used for the posix linker option
/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
05). Jika tidak ada pustaka yang dapat ditemukan, kembalikan
>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
14

The exact functionality is system dependent

ctypes. utilitas. find_msvcrt()

Jendela saja. kembalikan nama file pustaka runtime VC yang digunakan oleh Python, dan dengan modul ekstensi. Jika nama perpustakaan tidak dapat ditentukan,

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
14 dikembalikan

Jika Anda perlu mengosongkan memori, misalnya, yang dialokasikan oleh modul ekstensi dengan panggilan ke

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
17, penting agar Anda menggunakan fungsi di perpustakaan yang sama yang mengalokasikan memori

ctypes. FormatError([kode])

Jendela saja. Mengembalikan deskripsi tekstual dari kode kode kesalahan. Jika tidak ada kode kesalahan yang ditentukan, kode kesalahan terakhir digunakan dengan memanggil fungsi Windows api GetLastError

ctypes. GetLastError()

Jendela saja. Returns the last error code set by Windows in the calling thread. Fungsi ini memanggil fungsi Windows

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
_85 secara langsung, tidak mengembalikan salinan kode kesalahan ctypes-private

ctypes. get_errno()

Mengembalikan nilai saat ini dari salinan ctypes-private dari variabel sistem di utas panggilan

Memunculkan

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
_20 tanpa argumen

ctypes. get_last_error()

Windows only. returns the current value of the ctypes-private copy of the system

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
21 variable in the calling thread

Memunculkan

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
_22 tanpa argumen

ctypes. memmove(dst , src, count)

Sama seperti fungsi pustaka memmove C standar. salinan menghitung byte dari src ke dst. dst and src must be integers or ctypes instances that can be converted to pointers

ctypes. memset(dst , c , count)

Same as the standard C memset library function. fills the memory block at address dst with count bytes of value c. dst must be an integer specifying an address, or a ctypes instance

ctypes. POINTER(type)

This factory function creates and returns a new ctypes pointer type. Pointer types are cached and reused internally, so calling this function repeatedly is cheap. type must be a ctypes type

ctypes. pointer(obj)

Fungsi ini membuat instance pointer baru, menunjuk ke obj. The returned object is of the type

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
23

Note. If you just want to pass a pointer to an object to a foreign function call, you should use

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
24 which is much faster

ctypes. resize(obj , size)

This function resizes the internal memory buffer of obj, which must be an instance of a ctypes type. It is not possible to make the buffer smaller than the native size of the objects type, as given by

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
25, but it is possible to enlarge the buffer

ctypes. set_errno(value)

Set the current value of the ctypes-private copy of the system variable in the calling thread to value and return the previous value

Raises an

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
27 with argument
/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
31

ctypes. set_last_error(value)

Windows only. set the current value of the ctypes-private copy of the system

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
21 variable in the calling thread to value and return the previous value

Raises an

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
30 with argument
>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
31

ctypes. sizeof(obj_or_type)

Returns the size in bytes of a ctypes type or instance memory buffer. Does the same as the C

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
32 operator

ctypes. string_at(address , size=- 1)

This function returns the C string starting at memory address address as a bytes object. If size is specified, it is used as size, otherwise the string is assumed to be zero-terminated

Raises an

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
33 with arguments
>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
34,
>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
81

ctypes. WinError(code=None , descr=None)

Windows only. this function is probably the worst-named thing in ctypes. It creates an instance of OSError. If code is not specified,

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
36 is called to determine the error code. If descr is not specified, is called to get a textual description of the error

Changed in version 3. 3. An instance of used to be created.

ctypes. wstring_at(address , size=- 1)

This function returns the wide character string starting at memory address address as a string. If size is specified, it is used as the number of characters of the string, otherwise the string is assumed to be zero-terminated

Raises an

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
39 with arguments
>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
34,
>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
81

Data types

class ctypes. _CData

This non-public class is the common base class of all ctypes data types. Antara lain, semua instance tipe ctypes berisi blok memori yang menyimpan data yang kompatibel dengan C; . Another instance variable is exposed as ; this contains other Python objects that need to be kept alive in case the memory block contains pointers

Metode umum dari tipe data ctypes, ini semua adalah metode kelas (tepatnya, ini adalah metode dari )

from_buffer(source[ , offset])

Metode ini mengembalikan instance ctypes yang berbagi buffer dari objek sumber. Objek sumber harus mendukung antarmuka buffer yang dapat ditulisi. The optional offset parameter specifies an offset into the source buffer in bytes; the default is zero. If the source buffer is not large enough a is raised

Raises an

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
45 with arguments
>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
78,
>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
81,
>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
48

from_buffer_copy(source[ , offset])

Metode ini membuat instance ctypes, menyalin buffer dari buffer objek sumber yang harus dapat dibaca. The optional offset parameter specifies an offset into the source buffer in bytes; the default is zero. Jika buffer sumber tidak cukup besar, a dinaikkan

Raises an

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
45 with arguments
>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
78,
>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
81,
>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
48

from_address(address)

This method returns a ctypes type instance using the memory specified by address which must be an integer

This method, and others that indirectly call this method, raises an

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
54 with argument
>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
34

from_param(obj)

Metode ini mengadaptasi obj ke tipe ctypes. Ini disebut dengan objek aktual yang digunakan dalam pemanggilan fungsi asing ketika tipenya ada di tuple

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
62 fungsi asing;

All ctypes data types have a default implementation of this classmethod that normally returns obj if that is an instance of the type. Beberapa tipe menerima objek lain juga

in_dll(library , name)

This method returns a ctypes type instance exported by a shared library. name adalah nama simbol yang mengekspor data, pustaka adalah pustaka bersama yang dimuat

Variabel instan umum dari tipe data ctypes

_b_dasar_

Terkadang instance data ctypes tidak memiliki blok memori yang dikandungnya, melainkan berbagi bagian dari blok memori dari objek dasar. The read-only member is the root ctypes object that owns the memory block

_b_needsfree_

This read-only variable is true when the ctypes data instance has allocated the memory block itself, false otherwise

_objects

This member is either

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
14 or a dictionary containing Python objects that need to be kept alive so that the memory block contents is kept valid. Objek ini hanya diekspos untuk debugging;

Tipe data dasar

kelas tipe. _SimpleCData

Kelas non-publik ini adalah kelas dasar dari semua tipe data ctypes fundamental. It is mentioned here because it contains the common attributes of the fundamental ctypes data types. adalah subkelas dari , sehingga mewarisi metode dan atributnya. tipe data ctypes yang tidak dan tidak mengandung pointer sekarang dapat diasamkan

Instances have a single attribute

value

Atribut ini berisi nilai sebenarnya dari instance. Untuk tipe integer dan pointer, itu adalah integer, untuk tipe karakter, itu adalah objek atau string byte karakter tunggal, untuk tipe pointer karakter itu adalah objek atau string byte Python

Ketika atribut

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
_56 diambil dari instance ctypes, biasanya objek baru dikembalikan setiap kali. does not implement original object return, always a new object is constructed. Hal yang sama berlaku untuk semua instance objek ctypes lainnya

Fundamental data types, when returned as foreign function call results, or, for example, by retrieving structure field members or array items, are transparently converted to native Python types. Dengan kata lain, jika fungsi asing memiliki

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
77 dari , Anda akan selalu menerima objek Python bytes, bukan instance

Subkelas dari tipe data fundamental tidak mewarisi perilaku ini. Jadi, jika fungsi asing

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
_77 adalah subkelas dari , Anda akan menerima turunan dari subkelas ini dari pemanggilan fungsi. Tentu saja, Anda bisa mendapatkan nilai pointer dengan mengakses atribut
>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
56

Ini adalah tipe data ctypes dasar

kelas tipe. c_byte

Mewakili tipe data C signed char , dan menginterpretasikan nilainya sebagai bilangan bulat kecil. Konstruktor menerima penginisialisasi bilangan bulat opsional; .

kelas tipe. c_char

Mewakili tipe data C char , dan menginterpretasikan nilainya sebagai karakter tunggal. Konstruktor menerima penginisialisasi string opsional, panjang string harus tepat satu karakter.

kelas tipe. c_char_p

Mewakili tipe data C char* saat menunjuk ke string yang diakhiri dengan nol. For a general character pointer that may also point to binary data,

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
69 must be used. Konstruktor menerima alamat integer, atau objek byte.

kelas tipe. c_double

Mewakili tipe data C double . Konstruktor menerima penginisialisasi float opsional.

kelas tipe. c_longdouble

Mewakili tipe data C long double . Konstruktor menerima penginisialisasi float opsional. Pada platform di mana

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
_70 itu adalah alias untuk.

kelas tipe. c_float

Mewakili tipe data C float . Konstruktor menerima penginisialisasi float opsional.

kelas tipe. c_int

Mewakili tipe data C bertanda tangan int . Konstruktor menerima penginisialisasi bilangan bulat opsional; . Pada platform di mana

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
_72 itu adalah alias untuk.

kelas tipe. c_int8

Mewakili tipe data C 8-bit bertanda tangan int . Biasanya alias untuk.

kelas tipe. c_int16

Mewakili tipe data C 16-bit bertanda tangan int . Biasanya alias untuk.

kelas tipe. c_int32

Mewakili tipe data C 32-bit bertanda tangan int . Biasanya alias untuk.

kelas tipe. c_int64

Mewakili tipe data C 64-bit bertanda tangan int . Biasanya alias untuk.

kelas tipe. c_long

Mewakili tipe data C bertanda panjang . Konstruktor menerima penginisialisasi bilangan bulat opsional; .

kelas tipe. c_longlong

Mewakili tipe data C bertanda long long . Konstruktor menerima penginisialisasi bilangan bulat opsional; .

kelas tipe. c_short

Mewakili tipe data C bertanda tangan pendek . Konstruktor menerima penginisialisasi bilangan bulat opsional; .

class ctypes. c_size_t

Represents the C

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
78 datatype

class ctypes. c_ssize_t

Represents the C

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
79 datatype

New in version 3. 2

class ctypes. c_ubyte

Represents the C unsigned char datatype, it interprets the value as small integer. The constructor accepts an optional integer initializer; no overflow checking is done.

class ctypes. c_uint

Represents the C unsigned int datatype. The constructor accepts an optional integer initializer; no overflow checking is done. On platforms where

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
72 it is an alias for .

class ctypes. c_uint8

Represents the C 8-bit unsigned int datatype. Usually an alias for .

class ctypes. c_uint16

Represents the C 16-bit unsigned int datatype. Usually an alias for .

class ctypes. c_uint32

Mewakili tipe data C 32-bit unsigned int . Usually an alias for .

class ctypes. c_uint64

Represents the C 64-bit unsigned int datatype. Usually an alias for .

class ctypes. c_ulong

Mewakili tipe data C unsigned long . Konstruktor menerima penginisialisasi bilangan bulat opsional; .

kelas tipe. c_ulonglong

Mewakili tipe data C unsigned long long . Konstruktor menerima penginisialisasi bilangan bulat opsional; .

kelas tipe. c_ushort

Mewakili tipe data C unsigned pendek . Konstruktor menerima penginisialisasi bilangan bulat opsional; .

kelas tipe. c_void_p

Mewakili tipe C void* . Nilai direpresentasikan sebagai bilangan bulat. Konstruktor menerima penginisialisasi bilangan bulat opsional.

kelas tipe. c_wchar

Mewakili tipe data C wchar_t , dan menafsirkan nilai sebagai string unicode karakter tunggal. Konstruktor menerima penginisialisasi string opsional, panjang string harus tepat satu karakter.

kelas tipe. c_wchar_p

Mewakili tipe data C wchar_t* , yang harus berupa penunjuk ke lebar yang diakhiri dengan nol . Konstruktor menerima alamat integer, atau string.

kelas tipe. c_bool

Merepresentasikan tipe data C bool (lebih tepatnya, _Bool from C99). Its value can be

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
86 or
>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)  
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>
21, and the constructor accepts any object that has a truth value.

kelas tipe. HASILNYA

Jendela saja. Mewakili nilai

>>> c_int()
c_long(0)
>>> c_wchar_p("Hello, World")
c_wchar_p(140018365411392)
>>> c_ushort(-3)
c_ushort(65533)
>>>
2, yang berisi informasi keberhasilan atau kesalahan untuk pemanggilan fungsi atau metode

kelas tipe. py_object

Mewakili tipe data C * . Memanggil ini tanpa argumen membuat pointer

>>> cdll.LoadLibrary("libc.so.6")  
<CDLL 'libc.so.6', handle .. at ...>
>>> libc = CDLL("libc.so.6")       
>>> libc                           
<CDLL 'libc.so.6', handle .. at ...>
>>>
13 * .

Modul

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
_90 menyediakan beberapa tipe data khusus Windows lainnya, misalnya
>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
91,
>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
92, atau
>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
93. Beberapa struktur yang berguna seperti
>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  
<_FuncPtr object at 0x...>
>>>
_94 atau
/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
90 juga didefinisikan

Tipe data terstruktur

kelas tipe. Serikat(*args , **kw)

Kelas dasar abstrak untuk serikat pekerja dalam urutan byte asli

kelas tipe. BigEndianUnion(*args , **kw)

Kelas dasar abstrak untuk serikat pekerja dalam urutan byte big endian

Baru di versi 3. 11

kelas tipe. LittleEndianUnion(*args , **kw)

Kelas dasar abstrak untuk serikat pekerja dalam urutan byte endian kecil

Baru di versi 3. 11

kelas tipe. BigEndianStructure(*args , **kw)

Kelas dasar abstrak untuk struktur dalam urutan byte big endian

kelas tipe. LittleEndianStructure(*args , **kw)

Kelas dasar abstrak untuk struktur dalam urutan bit endian byte

Struktur dan gabungan dengan urutan byte non-asli tidak dapat berisi bidang tipe penunjuk, atau tipe data lain yang berisi bidang tipe penunjuk

kelas tipe. Struktur(*args , **kw)

Kelas dasar abstrak untuk struktur dalam urutan byte asli

Struktur beton dan tipe gabungan harus dibuat dengan mensubklasifikasikan salah satu dari tipe ini, dan setidaknya menentukan variabel kelas. akan membuat s yang memungkinkan membaca dan menulis bidang dengan akses atribut langsung. Ini adalah

_bidang_

Urutan mendefinisikan bidang struktur. Item harus 2-tupel atau 3-tupel. Item pertama adalah nama bidang, item kedua menentukan jenis bidang;

Untuk bidang tipe bilangan bulat seperti , item opsional ketiga dapat diberikan. Itu harus berupa bilangan bulat positif kecil yang menentukan lebar bit bidang

Nama bidang harus unik dalam satu struktur atau gabungan. Ini tidak dicentang, hanya satu bidang yang dapat diakses saat nama diulang

Dimungkinkan untuk mendefinisikan variabel kelas setelah pernyataan kelas yang mendefinisikan subkelas Struktur, ini memungkinkan pembuatan tipe data yang secara langsung atau tidak langsung mereferensikan diri mereka sendiri

>>> cdll.kernel32.GetModuleHandleA(None)  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Procedure probably called with not enough arguments (4 bytes missing)
>>>

>>> windll.msvcrt.printf(b"spam")  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Procedure probably called with too many arguments (4 bytes in excess)
>>>
_7

Variabel kelas harus, bagaimanapun, didefinisikan sebelum tipe pertama kali digunakan (sebuah instance dibuat, dipanggil, dan seterusnya). Penugasan selanjutnya ke variabel kelas akan memunculkan AttributeError

Dimungkinkan untuk mendefinisikan sub-subclass dari tipe struktur, mereka mewarisi bidang dari kelas dasar ditambah yang ditentukan dalam sub-subclass, jika ada

_Pak_

Bilangan bulat kecil opsional yang memungkinkan penggantian penyelarasan bidang struktur dalam instance. harus sudah ditentukan saat ditugaskan, jika tidak maka tidak akan berpengaruh

_anonim_

Urutan opsional yang mencantumkan nama bidang tanpa nama (anonim). harus sudah ditentukan saat ditugaskan, jika tidak maka tidak akan berpengaruh

Bidang yang tercantum dalam variabel ini harus bidang jenis struktur atau gabungan. akan membuat deskriptor dalam tipe struktur yang memungkinkan akses bidang bersarang secara langsung, tanpa perlu membuat struktur atau bidang gabungan

Berikut adalah contoh jenis (Windows)

>>> cdll.kernel32.GetModuleHandleA(None)  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Procedure probably called with not enough arguments (4 bytes missing)
>>>

>>> windll.msvcrt.printf(b"spam")  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Procedure probably called with too many arguments (4 bytes in excess)
>>>
_8

Struktur

>>> cdll.kernel32[1]  
<_FuncPtr object at 0x...>
>>> cdll.kernel32[0]  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 310, in __getitem__
    func = _StdcallFuncPtr(name, self)
AttributeError: function ordinal 0 not found
>>>
_09 menjelaskan tipe data COM, bidang
>>> cdll.kernel32[1]  
<_FuncPtr object at 0x...>
>>> cdll.kernel32[0]  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 310, in __getitem__
    func = _StdcallFuncPtr(name, self)
AttributeError: function ordinal 0 not found
>>>
10 menentukan salah satu bidang gabungan mana yang valid. Karena bidang
>>> cdll.kernel32[1]  
<_FuncPtr object at 0x...>
>>> cdll.kernel32[0]  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 310, in __getitem__
    func = _StdcallFuncPtr(name, self)
AttributeError: function ordinal 0 not found
>>>
11 didefinisikan sebagai bidang anonim, sekarang dimungkinkan untuk mengakses anggota secara langsung dari instance TYPEDESC.
>>> cdll.kernel32[1]  
<_FuncPtr object at 0x...>
>>> cdll.kernel32[0]  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 310, in __getitem__
    func = _StdcallFuncPtr(name, self)
AttributeError: function ordinal 0 not found
>>>
12 dan
>>> cdll.kernel32[1]  
<_FuncPtr object at 0x...>
>>> cdll.kernel32[0]  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 310, in __getitem__
    func = _StdcallFuncPtr(name, self)
AttributeError: function ordinal 0 not found
>>>
13 setara, tetapi yang pertama lebih cepat karena tidak perlu membuat instance gabungan sementara

>>> cdll.kernel32.GetModuleHandleA(None)  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Procedure probably called with not enough arguments (4 bytes missing)
>>>

>>> windll.msvcrt.printf(b"spam")  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Procedure probably called with too many arguments (4 bytes in excess)
>>>
_9

Dimungkinkan untuk mendefinisikan sub-subclass dari struktur, mereka mewarisi bidang dari kelas dasar. Jika definisi subclass memiliki variabel terpisah, bidang yang ditentukan di sini ditambahkan ke bidang kelas dasar

Konstruktor struktur dan gabungan menerima argumen posisi dan kata kunci. Argumen posisi digunakan untuk menginisialisasi bidang anggota dalam urutan yang sama seperti saat muncul. Argumen kata kunci dalam konstruktor ditafsirkan sebagai penetapan atribut, sehingga mereka akan menginisialisasi dengan nama yang sama, atau membuat atribut baru untuk nama yang tidak ada di

Array dan pointer

kelas tipe. Array(*args)

Kelas dasar abstrak untuk array

Cara yang disarankan untuk membuat tipe array konkret adalah dengan mengalikan tipe data apa pun dengan integer non-negatif. Sebagai alternatif, Anda dapat mensubklasifikasikan tipe ini dan mendefinisikan serta mengklasifikasikan variabel. Elemen array dapat dibaca dan ditulis menggunakan akses subskrip dan irisan standar;

_panjangnya_

Bilangan bulat positif yang menentukan jumlah elemen dalam larik. Subskrip di luar jangkauan menghasilkan. Akan dikembalikan oleh

_Tipe_

Menentukan jenis setiap elemen dalam array

Konstruktor subkelas array menerima argumen posisi, digunakan untuk menginisialisasi elemen secara berurutan

kelas tipe. _Penunjuk

Kelas dasar privat dan abstrak untuk pointer

Jenis penunjuk konkret dibuat dengan memanggil dengan jenis yang akan ditunjuk;

Jika sebuah pointer menunjuk ke sebuah array, elemen-elemennya dapat dibaca dan ditulis menggunakan subskrip standar dan akses slice. Objek penunjuk tidak memiliki ukuran, jadi akan dinaikkan. Subskrip negatif akan membaca dari memori sebelum penunjuk (seperti pada C), dan subskrip di luar jangkauan mungkin akan macet dengan pelanggaran akses (jika Anda beruntung)

_Tipe_

Menentukan jenis yang ditunjuk

isi

Mengembalikan objek yang menjadi tujuan penunjuk. Menetapkan ke atribut ini mengubah penunjuk untuk menunjuk ke objek yang ditetapkan

Bisakah kita memiliki array pointer fungsi?

4) Seperti pointer normal, kita dapat memiliki array pointer fungsi . Contoh di bawah ini pada poin 5 menunjukkan sintaks untuk array pointer.

Apa pointer dalam array Python?

Pada dasarnya, mereka adalah variabel yang menyimpan alamat memori dari variabel lain . Untuk penyegaran pada pointer, Anda dapat mempertimbangkan untuk memeriksa ikhtisar ini pada C Pointer. Pada artikel ini, Anda akan mendapatkan pemahaman yang lebih baik tentang model objek Python dan mempelajari mengapa pointer di Python tidak benar-benar ada.

Apakah ada penunjuk fungsi di Python?

Jadi, fungsi juga merupakan objek dalam python . Seperti yang kita ketahui bahwa setiap objek memiliki idnya masing-masing, sehingga kita dapat mengakses dan menyimpan id tersebut ke dalam sebuah variabel. Pada program di atas, fun adalah function pointer, yaitu menunjuk ke fungsi i. e. kesenanganku().

Bagaimana Anda membuat array fungsi dengan Python?

Dengan Python, Anda dapat membuat tipe data baru, yang disebut array menggunakan paket NumPy. Array NumPy dioptimalkan untuk analisis numerik dan hanya berisi satu tipe data. Anda terlebih dahulu mengimpor NumPy dan kemudian menggunakan fungsi array() untuk membuat array . Fungsi array() mengambil daftar sebagai masukan.