如何使用Python CFFI正确包装C库

时间:2016-08-16 16:24:52

标签: python c python-cffi

我试图包装一个非常简单的C库,其中只包含两个.C源文件: dbc2dbf.c blast.c

我正在执行以下操作(来自文档):

import os
from cffi import FFI
blastbuilder = FFI()
ffibuilder = FFI()
with open(os.path.join(os.path.dirname(__file__), "c-src/blast.c")) as f:
    blastbuilder.set_source("blast", f.read(), libraries=["c"])
with open(os.path.join(os.path.dirname(__file__), "c-src/blast.h")) as f:
    blastbuilder.cdef(f.read())
blastbuilder.compile(verbose=True)

with open('c-src/dbc2dbf.c','r') as f:
    ffibuilder.set_source("_readdbc",
                          f.read(),
                          libraries=["c"])

with open(os.path.join(os.path.dirname(__file__), "c-src/blast.h")) as f:
    ffibuilder.cdef(f.read(), override=True)

if __name__ == "__main__":
    # ffibuilder.include(blastbuilder)
    ffibuilder.compile(verbose=True)

这不太合适。我想我没有正确地包括 blast.c ;

任何人都可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

这是解决方案(已测试):

import os
from cffi import FFI

ffibuilder = FFI()

PATH = os.path.dirname(__file__)

with open(os.path.join(PATH, 'c-src/dbc2dbf.c'),'r') as f:
    ffibuilder.set_source("_readdbc",
                          f.read(),
                          libraries=["c"],
                          sources=[os.path.join(PATH, "c-src/blast.c")],
                          include_dirs=[os.path.join(PATH, "c-src/")]
                          )
ffibuilder.cdef(
    """
    static unsigned inf(void *how, unsigned char **buf);
    static int outf(void *how, unsigned char *buf, unsigned len);
    void dbc2dbf(char** input_file, char** output_file);
    """
)

with open(os.path.join(PATH, "c-src/blast.h")) as f:
    ffibuilder.cdef(f.read(), override=True)

if __name__ == "__main__":
    ffibuilder.compile(verbose=True)