2019年3月5日 星期二

[python] 最簡單的方法, 呼叫 python 模組 using cython


How to invoke python code from C using cython

井民全, Jing, mqjing@gmail.com


這文章 go through 了一次, 如何從 C 來呼叫 python module 的 code.




內容包含:

  • 最簡單的 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
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 main.c
#include Python.h // 兩邊加上角括號
#include "bridge.h" int main() { Py_Initialize(); PyInit_bridge(); // init the bridge module call_python_module(); // call bridge Py_Finalize(); return 0; }
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 #include "bridge.h" int main() { Py_Initialize(); PyInit_bridge(); // init the bridge module call_python_module(); // call bridge Py_Finalize(); return 0; }


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