python调用c代码2

时间:2023-03-08 15:27:05
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