Python Ctypes 结构体指针处理(函数参数,函数返回)
2012-03-26 00:00
609 查看
C函数需要传递结构体指针是常事,但是和Python交互就有点麻烦事了,经过研究也可以了。
<结构体指针作为函数参数>
来看下C测试例子:
这里test里面需要传入结构体指针,函数中的实现很简单,就是改变x 和 y 的值这个函数将被python调用。
使用Python调用时,需要模拟申明个结构体(class):
Usage:
<函数返回结构体指针>
C函数测试例子改成如下:
Python程序处理如下:
关于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.
$(document).ready(function(){dp.SyntaxHighlighter.HighlightAll('code');});
原文链接:
http://blog.csdn.net/crazyjixiang/article/details/6832920
<结构体指针作为函数参数>
来看下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.
$(document).ready(function(){dp.SyntaxHighlighter.HighlightAll('code');});
原文链接:
http://blog.csdn.net/crazyjixiang/article/details/6832920
相关文章推荐
- Python Ctypes结构体指针处理(函数参数,函数返回)
- 结构体指针与结构体名做函数参数对比
- C++ 利用指针和结构体实现一个函数返回多个值
- 指针作为函数参数(处理数组的四种方式)
- C++数组(二维数组)与指针 以及 函数传递/返回指针和数组参数
- 指向指针的指针在函数中参数传递并返回
- 结构体变量指针作为函数参数
- 基类中定义的虚函数在派生类中重新定义时,其函数原型,包括返回类型、函数名、参数个数、参数类型及参数的先后顺序,都必须与基类中的原型完全相同 but------> 可以返回派生类对象的引用或指针
- [编程] C语言结构体指针作为函数参数
- 如何正确使用指针(指针作为输出型参数)与结构体指针作为函数参数
- python学习笔记——函数可变参数处理
- 【C语言提高37】结构体元素做函数参数与结构指针做函数参数
- 结构体变量、结构指针变量、结构数组作为函数的参数应用实例分析
- C#调用参数为函数指针的API函数 - 以SetUnhandledExceptionFilter为例编写一个全局异常处理程序
- 结构体变量、结构指针变量、结构数组作为函数的参数应用实例分析
- 函数传出参数,用指针作为函数的传出参数实现多值返回
- 学习回调函数同时引申出用函数参数返回一些值或指针
- python--函数的返回值、函数参数的使用、名称空间与作用域、函数嵌套、函数对象
- 修改程序清单7.7中的3个数组处理函数,使之使用两个指针参数来表示区间.
- Python小白学习之路(十)—【函数】【函数返回值】【函数参数】