Python Ctypes 结构体指针处理(函数参数,函数返回)
C函数需要传递结构体指针是常事,但是和Python交互就有点麻烦事了,经过研究也可以了。
<结构体指针作为函数参数>
来看下C测试例子:
- #include <stdio.h>
- typedef struct StructPointerTest* StructPointer;
- struct StructPointerTest{
- int x;
- int y;
- };
- void test(StructPointer p) {
- p->x = 101;
- p->y = 201;
- }
这里test里面需要传入结构体指针,函数中的实现很简单,就是改变x 和 y 的值这个函数将被python调用。
使用Python调用时,需要模拟申明个结构体(class):
- from ctypes import *
- class StructPointerTest(Structure):
- _fields_ =[('x', c_int),
- ('y', c_int)]
Usage:
- ##Structure Pointer Operation
- SPTobj = pointer(StructPointerTest(1, 2))
- print SPTobj
- print SPTobj.contents.x
- print SPTobj.contents.y
<函数返回结构体指针>
C函数测试例子改成如下:
- StructPointer test() {
- StructPointer p = (StructPointer)malloc(sizeof(struct StructPointerTest));
- p->x = 101;
- p->y = 201;
- return p;
- }
Python程序处理如下:
- from ctypes import *
- class StructPointer(Structure):
- pass
- StructPointer._fields_=[('x', c_int),
- ('y', c_int),
- ('next', POINTER(StructPointer))]
- lib = cdll.LoadLibrary('./StructPointer.so')
- lib.test.restype = POINTER(StructPointer)
- p = lib.test()
- print p.contents.x
相关推荐
IT之家 2020-03-11
graseed 2020-10-28
zbkyumlei 2020-10-12
SXIAOYI 2020-09-16
jinhao 2020-09-07
impress 2020-08-26
liuqipao 2020-07-07
淡风wisdon大大 2020-06-06
yoohsummer 2020-06-01
chenjia00 2020-05-29
baike 2020-05-19
扭来不叫牛奶 2020-05-08
hxmilyy 2020-05-11
黎豆子 2020-05-07
xiongweiwei00 2020-04-29
Cypress 2020-04-25
冰蝶 2020-04-20