How to invoke pyx code from C
井民全, Jing, mqjing@gmail.com
已經知道如果程式碼使用 cython language 撰寫, 將來的執行速度會是原來 python 的 10 倍.
所以我來 go through 了一次, 如何從 C 來呼叫 pyx module 的 code.
所以我來 go through 了一次, 如何從 C 來呼叫 pyx module 的 code.
內容包含:
- 最簡單的 pyx code
- 如何自動轉換 pyx code 到 C 產生 object files
- 最簡單的呼叫 pyx module 範例 from C
Enjoy
Jing.
Pyx Code
cdef public void my_python_module():
print('1234') |
Quick
# transfer and build
cython my_python.pyx
gcc my_python.c -o my_python.o -shared -pthread -fPIC -fwrapv -O2 -Wall -fno-strict-aliasing -I/usr/include/python3.5
# usage
----------- main.c -------------
#include
#include "my_python.h"
int main() {
Py_Initialize();
PyInit_my_python(); // ---- init the python module
my_python_module(); // ---- call my python module
Py_Finalize();
return 0;
}
---------------------------------------
gcc main.c -ldl my_python.o -I/usr/include/python3.5 -L/usr/lib/python3.5/config-3.5m-x86_64-linux-gnu -lpython3.5
# run
./a.out
# transfer and build
cython my_python.pyx
gcc my_python.c -o my_python.o -shared -pthread -fPIC -fwrapv -O2 -Wall -fno-strict-aliasing -I/usr/include/python3.5
# usage
----------- main.c ------------- #include --------------------------------------- gcc main.c -ldl my_python.o -I/usr/include/python3.5 -L/usr/lib/python3.5/config-3.5m-x86_64-linux-gnu -lpython3.5 # run ./a.out |
Detail
Transfer the pyx code to C module
Step 1: Generate the C code
cython my_python.pyx
Or
python setup.py build_ext --inplace
|
Result
Step 2: Build the object file
gcc my_python.c -o my_python.o -shared -pthread -fPIC -fwrapv -O2 -Wall -fno-strict-aliasing -I/usr/include/python3.5
Result
Usage
main.c
#include
#include "my_python.h"
int main() {
Py_Initialize();
PyInit_my_python(); // <---- init="" module="" python="" span="" the="">---->
my_python_module(); // <---- call="" module="" my="" python="" span="">---->
Py_Finalize();
return 0;
}
|
Build and Run
Step 1: build the source code
gcc main.c -ldl my_python.o -I/usr/include/python3.5 -L/usr/lib/python3.5/config-3.5m-x86_64-linux-gnu -lpython3.5
Step 2: Setup the shared library path, LD_LIBRARY_PATH
LD_LIBRARY_PATH=.
export LD_LIBRARY_PATH
Step 3: Run
./a.out