(已解决) -> 如何获取 CFFI 和 setuptools 来查找 C 文件和标头

(solved) -> How to get CFFI and setuptools to find C files and headers

提问人:Fergus Rooney 提问时间:6/14/2023 最后编辑:Fergus Rooney 更新时间:6/14/2023 访问量:126

问:

我已经使用 CFFI 编写了一个 c 扩展包,我正在尝试研究如何使用 setuptools 构建它。我的包裹如下所示:

pkgName/
    pyproject.toml
    setup.py
    src/
       pkgName/
              build_cffi.py # Compiles C extension with CFFI
              mainCfile.C
              mainCfile.h
              other.h
              wrapper.py
              __init__.py

我的build_cffi.py如下所示:

ffibuilder.set_source(
    "c_binding",
    """
     #include "mainCfile.h"   // the C header of the library
""",
    sources=['mainCfile.c'], include_dirs = [os.path.dirname(os.path.realpath(__file__))]
)
ffibuilder.cdef(
    """
    void test_print(int to_print);
"""
)
if __name__ == "__main__":
    ffibuilder.compile(verbose=True)

我的 setup.py 是这样的

from setuptools import setup
setup(
    setup_requires=["cffi>=1.0.0"],
    cffi_modules=["src/pkgName/build_cffi.py:ffibuilder"],
    install_requires=["cffi>=1.0.0"],
)

现在,当我从 src/pkgName 文件夹自行运行build_cffi.py时,它构建良好。但是,当我从包根目录运行时,编译失败并出现以下错误:python3 -m buildfatal error: mainCfile.h: No such file or directory

如何让 CFFI 和 setuptools 从 setuptools 中找到带有 c 标头的目录?我试图添加这个,但它没有区别。include_dirs = [os.path.dirname(os.path.realpath(__file__))])

编辑:找到解决方案

.c 和 .h 文件需要由 setuptools 添加到源代码分发中。这可以在文件中完成,但是您可以通过在函数中添加以下额外行来执行此操作:manifest.insetup.pysetup()

package_data={"": ["*.h", "*.c"]}.

我还必须对build_cffi.py文件进行以下更改:

ffibuilder.set_source(
    "pkgName.c_bindings", <- Changed to pkg.file 
    """
     #include "mainCfile.h"   
""",
    sources=["src/pkgName/mainCfile.c"], # <-- Make relative to root directory
    include_dirs=[os.path.dirname(os.path.realpath(__file__))],
)   
python setuptools python-cffi

评论

0赞 Armin Rigo 6/14/2023
尝试在该文件中执行操作?也许在某些情况下它的执行方式没有正确设置特殊变量......print(__file__)__file__

答: 暂无答案