13 กุมภาพันธ์ 2560

Published กุมภาพันธ์ 13, 2560 by with 0 comment

เรียกใช้โค้ดภาษาซีใน Python ด้วย cffi

เวลาปกติ เมื่อคุณต้องการเรียกใช้งานโค้ดภาษาซีในภาษา Python คุณอาจมองหาไลบรารี ctypes (อ่านบทความการใช้งาน ctypes ได้ที่ เขียนโมดูลภาษาไพทอน C/C++ ด้วย ctypes) แต่ไลบรารี ctypes มีการใช้งานที่ไม่สะดวกนัก บทความนี้ขอแนะนำโมดูล cffi

โมดูล cffi เป็น Foreign Function Interface สำหรับเรียกใช้งานโค้ดภาษาซีในภาษาไพทอน โดยคุณสามารถ "copy paste" การประกาศชนิดข้อมูลของภาษาซีรวมถึงหน้าที่ในการเรียกใช้งานได้

  • รองรับทั้ง Python 2 , 3 และ PyPy
  • ใช้ License: MIT
ตัวอย่างการใช้าน

>>> from cffi import FFI
>>> ffi = FFI()
>>> ffi.cdef("""
... int printf(const char *format, ...); // copy-pasted from the man page
... """)
>>> C = ffi.dlopen(None) # loads the entire C namespace
>>> arg = ffi.new("char[]", "world") # equivalent to C code: char arg[] = "world";
>>> C.printf("hi there, %s.\n", arg) # call printf
hi there, world.
17 # this is the return value
>>>

อ่านเอกสารการใช้งานได้ที่ http://cffi.readthedocs.org

0 ความคิดเห็น:

แสดงความคิดเห็น

แสดงความคิดเห็นได้ครับ :)