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 ))

 

你可能感兴趣的:(Python的点点滴滴(ctypes))