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; }使用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 Cinttype. Other return types can be specified by setting therestypeattribute of the function object.
本文详细介绍了如何在C语言中使用结构体指针,并通过Python进行调用,包括结构体定义、指针传递、函数返回结构体指针等关键步骤。同时提供了实例代码演示了这一过程。
2万+

被折叠的 条评论
为什么被折叠?



