使用 cffi 接口编译和调用扩展库函数

官方文档


编译库:

  假设要编译的文件为 xxx.c,xx.c,xxx.h  

from cffi import FFI

ffibuilder = FFI() 
'''声明xxx.h里的函数和全局变量'''
ffibuilder.cdef(open('xxx.h').read())
'''设置输出库名,C源文件,编译器参数'''
ffibuilder.set_source("_xxx_cffi",'''
                    #include "xxx.c"
                    #include "xx.c"
                    ''',libraries=[],extra_compile_args=['/MT'])

ffibuilder.compile(verbose=True)

  运行后将生成一个名为 _xxx_cffi.pyd 的库

  编译器的参数设置可以参考:https://docs.python.org/zh-cn/dev/distutils/apiref.html


 

调用库:

  使用C的数据类型:  

from _xxx_cffi import ffi, lib  

p = ffi.new("char[]", "hello, world")    # p is a 'char *'
q = ffi.new("char **", p)                # q is a 'char **'

  使用库里的数据类型:  

# typedef struct { int x, y; } foo_t;

''' C中的用法 '''
#foo_t v = { 1, 2 }; 
           
''' cffi 中使用 '''
v = ffi.new("foo_t *", [1, 2]) 

  调用库函数:

# int foo(short a, int b);

n = lib.foo(2, 3)     # returns a normal integer
lib.foo(40000, 3)     # raises OverflowError

 

 

posted @ 2021-01-21 19:56  Pio-GD  阅读(261)  评论(0编辑  收藏  举报