มีหลายวิธี wrap C/C++ functionality ให้ Python ในส่วนนี้เราจะดูวิธี wrap ด้วย SWIG ตัวเลือกอื่นๆ:
- Manual wrapping
- Using pyrex to wrap C code.
- Ctypes
- SIP
- Boost Python
SWIG (Simple Wrapper Interface Generator) wrap C code ให้ภาษาอื่นมากมาย: Perl, Python, PHP, Ruby, Tcl, C#, Common Lisp, Java, Modula-3, OCAML และ Scheme implementations
แต่จะพูดถึง Python เท่านั้น SWIG เป็น macro language เข้าใจ C code แล้วสร้าง wrapper code สำหรับภาษาที่ต้องการ
Installation
ใช้ “swigwin-3.0.12” windows installer ดาวน์โหลดจาก: https://www.swig.org/download.html ต้องการ Microsoft Visual Studio 14.0 หรือสูงกว่า
ตัวอย่าง: มี C function อยากเพิ่มให้ภาษาอื่น เช่น Tcl, Perl, Python, Java, C#
My c file คือ example.c
#include "example.h" int fact(int n) { if (n < 0) { return 0; } if (n == 0) { return 1; } else { return n * fact(n-1); } }Interface file:
ต้องเขียน “interface file” เป็น input ให้ SWIG example.i:
/* File: example.i */ %module example %{ #define SWIG_FILE_WITH_INIT #include "example.h" %} %include "example.h"Header file
int fact(int n);
Setup file:
from distutils.core import setup, Extension example_module = Extension('_example', sources=['example_wrap.c', 'example.c'], ) setup (name = 'example', version = '0.1', author = "SWIG Docs", description = """Simple swig example from docs""", ext_modules = [example_module], py_modules = ["example"], )Creating the wrapper
สร้าง python wrapper ด้วย interface file (example.i):
>swig -python example.i
จะได้ไฟล์ wrapper ใหม่ ชื่อ “example_wrap.c” หรือ “Your_File_Name_wrapper_Your_language_extension”
Built the extension
>python setup.py build_ext running build_ext building '_example' extension creating build creating build\temp.win32-3.6 creating build\temp.win32-3.6\Release ….
เสร็จแล้วสามารถ wrap C ให้ Python ได้ ทดสอบ:
C:\Users\rajesh>mkdir swigExample && cd swigExample C:\Users\rajesh\swigExample>virtualenv swigenv Using base prefix 'c:\\python\\python361' New python executable in C:\Users\rajesh\swigExample\swigenv\Scripts\python.exe Installing setuptools, pip, wheel...done. C:\Users\rajesh\swigExample>.\swigenv\Scripts\activate (swigenv) C:\Users\rajesh\swigExample>python
import function และ run:
>>> from example import fact >>> fact(6) 720