1. 程式人生 > >在Python中來呼叫C Ex

在Python中來呼叫C Ex

1. 編寫 .c 檔案

// test1.c
int add(int a, int b){
    return a+b;
}

// test2.c
int sub(int a, int b){
    return a-b;
}

2. 編譯動態連結庫

本文只討論Linux下的編譯方法,windows下需要使用VC6編譯dll檔案,暫不討論。 在檔案數目較少的情況下直接編譯很方便,使用gcc或者g++,加share引數: gcc -fpic -c test1.c -o test1.o gcc -fpic -c test2.c -o test2.o gcc -shared -o test.so

test1.o test2.o

3. 編寫介面函式

# test.py
import ctypes
test = ctypes.CDLL('./test.so')
add = test.add
sub = test.sub

4. 引用

直接import寫好的介面檔案 test.py 就可以:

from test import *
a = int(input('a='))
b = int(input('b='))
print('a + b =', add(a, b), 'a - b =', sub(a,b))