python调用c代码2
1、生成动态链接库
[root@typhoeus79 c]# more head.c #include <stdio.h> #include <stdlib.h> typedef struct _point{ int x; int y; }Point; Point * InitPoint(int x,int y) { Point *p = (Point *)malloc(sizeof(Point)); p->x = x; p->y = y; return p; } Point * Incre(Point * p) { p->x = p->x + 1; p->y = p->y + 1; return p; } gcc -fPIC -shared -o libhead.so ./head.c
python调用
[root@typhoeus79 ice_test_m c]# more test.py #!/usr/bin/env python2.7 #-*- coding:utf-8 -*- from ctypes import * class Point(Structure): _fields_ = [("x",c_int),("y",c_int)] if __name__ == ‘__main__‘: ddl = CDLL("./libhead.so") ddl.InitPoint.restype = POINTER(Point) p = ddl.InitPoint(5,6); print p.contents.x print p.contents.y [root@typhoeus79 ice_test_m c]# ./test.py 5 6
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。