python函数参数类型可以是结构体吗_Python Ctypes结构体指针处理(函数参数,函数返回) | 学步园...

参考网址:

http://www.2cto.com/kf/201109/106444.html

本文演示了在python中调用C语言生成的动态库,返回结构体指针,并进行输出!

test.c(动态库源代码)

// 编译生成动态库: gcc -g -fPIC -shared -o libtest.so test.c

#include

#include

#include

typedef struct StructPointerTest

{

char name[20];

int age;

}StructPointerTest, *StructPointer;

StructPointer test()// 返回结构体指针

{

StructPointer p = (StructPointer)malloc(sizeof(StructPointerTest));

strcpy(p->name, "Joe");

p->age = 20;

return p;

}

编译:gcc -g -fPIC -shared -o libtest.so test.c

call.py(python调用C语言生成的动态库):

#!/bin/env python

# coding=UTF-8

from ctypes import *

#python中结构体定义

class StructPointer(Structure):

_fields_ = [("name", c_char * 20), ("age", c_int)]

if __name__ == "__main__":

lib = cdll.LoadLibrary("./libtest.so")

lib.test.restype = POINTER(StructPointer)

p = lib.test()

print "%s: %d" %(p.contents.name, p.contents.age)

最后运行结果:

[zcm@c_py #112]$make clean

rm -f *.o libtest.so

[zcm@c_py #113]$make

gcc -g -fPIC -shared -o libtest.so test.c

[zcm@c_py #114]$./call.py

Joe: 20

[zcm@c_py #115]$

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值