简体   繁体   English

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

[英]How to properly wrap a C library with Python CFFI

I am trying to wrap a very simple C library containing only two .C source files: dbc2dbf.c and blast.c 我试图包装一个非常简单的C库,其中只包含两个.C源文件: dbc2dbf.cblast.c

I am doing the following (from the documentation): 我正在做以下(来自文档):

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)

This is not quite working. 这不太合适。 I think I am not including blast.c correctly; 我想我没有正确地包括blast.c ;

can anyone help? 有人可以帮忙吗?

Here is the solution (tested): 这是解决方案(已测试):

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM