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
關於resttype可以參見 Tutorial : By default functions are assumed to return the C
int type. Other return types can be specified by setting the
restype attribute of the function object.