How to invoke python code from C using cython
井民全, Jing, mqjing@gmail.com
內容包含:
- 最簡單的 python code
- 撰寫最簡單的 cython module 來呼叫 python function
- 如何把 cython 模組 轉成 object, 讓 C 呼叫
- 最簡單的方法呼叫 cython module 使用 C
Enjoy
Jing.
Pytyon Code
my_python.py
def my_python_module():
print('1234')
|
Quick
# transfer and build the object
cython my_python.py
gcc my_python.c -o my_python.o -shared -pthread -fPIC -fwrapv -O2 -Wall -fno-strict-aliasing -I/usr/include/python3.5
# create bridge
bridge.pyx
cython bridge.pyx
gcc bridge.c -o bridge.o -shared -pthread -fPIC -fwrapv -O2 -Wall -fno-strict-aliasing -I/usr/include/python3.5
# usage
main.c
gcc main.c -ldl bridge.o -I/usr/include/python3.5 -L/usr/lib/python3.5/config-3.5m-x86_64-linux-gnu -lpython3.5
# run
./a.out
|
別忘記環境變數
(a) Bridge.so Path
LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH
(b) Python Module Path
PYTHONPATH=.:$PYTHONPATH
export PYTHONPATH
Detail
# Transfer the Source
cython my_python.py
gcc my_python.c -o my_python.o -shared -pthread -fPIC -fwrapv -O2 -Wall -fno-strict-aliasing -I/usr/include/python3.5
Create the bridge
bridge.pyx
from my_python import *
cdef public void call_python_module():
my_python_module()
|
cython bridge.pyx
gcc bridge.c -o bridge.o -shared -pthread -fPIC -fwrapv -O2 -Wall -fno-strict-aliasing -I/usr/include/python3.5
Usage
Write main.c
#include
|
Build the app
gcc main.c -ldl bridge.o -I/usr/include/python3.5 -L/usr/lib/python3.5/config-3.5m-x86_64-linux-gnu -lpython3.5
Setup Path Environment
(a) setup bridge.so path
Command
LD_LIBRARY_PATH=. export LD_LIBRARY_PATH
(b) Python Module Path
PYTHONPATH=.:$PYTHONPATH
Run your application
./a.out