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

关于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.



原文链接: http://blog.csdn.net/crazyjixiang/article/details/6832920

转载于:https://my.oschina.net/chen106106/blog/51105

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值