Python的点点滴滴(ctypes)

前俩天的调查方向:使用Python C extending来扩展Python,使其能够调用中间件的接口,实现起来比较繁琐。突然发现Python提供了ctypes这个包,可以很容易的使用Python直接调用C语言实现的接口,这使得开发的工作量大大降低,只是ctypes是基于libffi实现的跨语言封装,性能上可能会比使用C Extending来得慢一些,只是差距有多少,没时间验证了。

Sample 1:

1. 使用ctypes的第一步要导入ctypes module

from ctypes import *

2. 指定要访问的C语言动态库

hello = CDLL( 'libhello.so' )

3. 导入要访问的函数接口,严格一点,要指定接口的参数和返回值类型

myprint = hello.myprint
myprint.restype = c_int
myprint.argtypes = [ c_char_p ]

4. 在Python中,可以调用myprint来传递给C语言一个字符串

myprint( b'String from Python' )

Sample 2,回调函数:

1. 定义回调函数类型,类似C中的函数指针,如void ( * event_cb )( void * data, void * user_data ),定义为:

event_cb = CFUNCTYPE( None, c_void_p, c_void_p )

None表示返回值是void,也可以为其它类型,剩余俩个参数与C中的回调参数一致。

2. 定义Python回调函数:

def event_arrived( data, user_data ):
    #parsing data
    #...
    #return something or None

3. 注册回调函数:

register_events_listener( event_cb( event_arrived ), c_void_p( 0 ))

另外,使用ctypes可以避免GIL的问题。

Sample 3,传递结构体指针:

1. 定义结构体:

class MyStructure( Structure )
    _fields_ = [
        ( 'x', c_int ),
        ( 'y', c_int )]

2. 传递结构体:

_local = MyStructure( 1, 2 )
process_this_structure( byref( _local ))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值