手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

Python Ctypes 结构体指针处理(函数参数,函数返回)

[日期:2011-10-08] 来源:blog.csdn.net/crazyjixiang  作者:crazyjixiang [字体:大 中 小]

C函数需要传递结构体指针是常事,但是和Python交互就有点麻烦事了,经过研究也可以了。

<结构体指针作为函数参数>

来看下C测试例子:

  1. #include <stdio.h>   
  2. typedef struct StructPointerTest* StructPointer;  
  3. struct StructPointerTest{  
  4.         int x;  
  5.         int y;  
  6. };  
  7. void test(StructPointer p) {  
  8.         p->x = 101;  
  9.         p->y = 201;  
  10. }  

这里test里面需要传入结构体指针,函数中的实现很简单,就是改变x 和 y 的值这个函数将被python调用。

使用Python调用时,需要模拟申明个结构体(class):

  1. from ctypes import *  
  2. class StructPointerTest(Structure):   
  3.     _fields_ =[('x', c_int),  
  4.                ('y', c_int)]  

Usage:

  1. ##Structure Pointer Operation   
  2. SPTobj = pointer(StructPointerTest(1, 2))  
  3. print SPTobj  
  4. print SPTobj.contents.x   
  5. print SPTobj.contents.y  

<函数返回结构体指针>

C函数测试例子改成如下:

  1. StructPointer test() {  
  2.         StructPointer p = (StructPointer)malloc(sizeof(struct StructPointerTest));  
  3.         p->x = 101;  
  4.         p->y = 201;  
  5.         return p;  
  6. }  

Python程序处理如下:

  1. from ctypes import *  
  2. class StructPointer(Structure):  
  3.         pass  
  4.   
  5. StructPointer._fields_=[('x', c_int),  
  6.                         ('y', c_int),  
  7.                         ('next', POINTER(StructPointer))]  
  8.   
  9.   
  10. lib = cdll.LoadLibrary('./StructPointer.so')  
  11. lib.test.restype = POINTER(StructPointer)  
  12.   
  13. p = lib.test()  
  14. 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. linux
相关资讯       python  C 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款