python 調用 C 動態庫

首先是 C 的頭文件和源文件,html

#ifndef POINT_H                    
#define POINT_H                    
                                   
struct point                       
{                                  
    int x;                         
    int y;                         
};                                 
                                   
void point_print(struct point * p);
                                   
#endif /* POINT_H */  
#include <stdio.h>                         
#include "point.h"                         
                                           
void point_print(struct point * p)         
{                                          
    printf("x = %d, y = %d\n", p->x, p->y);
}                                          

下面是編譯命令,python

gcc -fPIC -shared point.c -o libpoint.so

下面是 python 代碼,函數

#! /usr/bin/python                
                                  
from ctypes import *              
                                  
class point(Structure):           
    _fields_ = [                  
        ("x", c_int),             
        ("y", c_int)              
    ]                             
                                  
ptr = point(10, 20)               
libpoint = CDLL("./libpoint.so")  
libpoint.point_print(byref(ptr))  
libpoint.point_print(pointer(ptr))

pointer 與 byref 的區別在於後者的效率高於前者,文檔中提到若是隻是向外部函數傳遞參數的引用,那麼使用 byref 便可。下面運行,spa

$ ./point.py  
x = 10, y = 20
x = 10, y = 20
$ 

另外諸如字節序、對齊、返回值處理、類型轉換和回調等等,能夠參考這裏code

相關文章
相關標籤/搜索