多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# 11.3 通过PyPI发布使用CMake/CFFI构建C/Fortran/Python项目 **NOTE**:*此示例代码可以在 https://github.com/dev-cafe/cmake-cookbook/tree/v1.0/chapter-11/recipe-03 中找到,其中有一个C++和Fortran示例。该示例在CMake 3.5版(或更高版本)中是有效的,并且已经在GNU/Linux、macOS和Windows上进行过测试。* 基于第9章第6节的示例,我们将重用前一个示例中的构建块,不过这次使用Python CFFI来提供Python接口,而不是pybind11。这个示例中,我们通过PyPI共享一个Fortran项目,这个项目可以是C或C++项目,也可以是任何公开C接口的语言,非Fortran就可以。 ## 准备工作 项目将使用如下的目录结构: ```shell . ├── account │ ├── account.h │ ├── CMakeLists.txt │ ├── implementation │ │ └── fortran_implementation.f90 │ ├── __init__.py │ ├── interface_file_names.cfg.in │ ├── test.py │ └── version.py ├── CMakeLists.txt ├── MANIFEST.in ├── README.rst └── setup.py ``` 主`CMakeLists.txt`文件和`account`下面的所有源文件(`account/CMakeLists.txt`除外)与第9章中的使用方式相同。`README.rst`文件与前面的示例相同。`setup.py`脚本比上一个示例多了一行(包含`install_require =['cffi']`的那一行): ```python # ... up to this line the script is unchanged setup( name=_this_package, version=version['__version__'], description='Description in here.', long_description=long_description, author='Bruce Wayne', author_email='bruce.wayne@example.com', url='http://example.com', license='MIT', packages=[_this_package], install_requires=['cffi'], include_package_data=True, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Science/Research', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.6' ], cmdclass={'build': extend_build()}) ``` `MANIFEST.in`应该与Python模块和包一起安装,并包含以下内容: ```txt include README.rst CMakeLists.txt recursive-include account *.h *.f90 CMakeLists.txt ``` `account`子目录下,我们看到两个新文件。一个`version.py`文件,其为`setup.py`保存项目的版本信息: ```python __version__ = '0.0.0' ``` 子目录还包含`interface_file_names.cfg.in`文件: ```cmake [configuration] header_file_name = account.h library_file_name = $<TARGET_FILE_NAME:account> ``` ## 具体实施 讨论一下实现打包的步骤: 1. 示例基于第9章第6节,使用Python CFFI扩展了`account/CMakeLists.txt`,增加以下指令: ```cmake file( GENERATE OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/interface_file_names.cfg INPUT ${CMAKE_CURRENT_SOURCE_DIR}/interface_file_names.cfg.in ) set_target_properties(account PROPERTIES PUBLIC_HEADER "account.h;${CMAKE_CURRENT_BINARY_DIR}/account_export.h" RESOURCE "${CMAKE_CURRENT_BINARY_DIR}/interface_file_names.cfg" ) install( TARGETS account LIBRARY DESTINATION account/lib RUNTIME DESTINATION account/lib PUBLIC_HEADER DESTINATION account/include RESOURCE DESTINATION account ) ``` 安装目标和附加文件准备好之后,就可以测试安装了。为此,会在某处创建一个新目录,我们将在那里测试安装。 2. 新创建的目录中,我们从本地路径运行pipenv install。调整本地路径,指向`setup.py`脚本保存的目录: ```shell $ pipenv install /path/to/fortran-example ``` 3. 现在在Pipenv环境中生成一个Python shell: ```shell $ pipenv run python ``` 4. Python shell中,可以测试CMake包: ```shell >>> import account >>> account1 = account.new() >>> account.deposit(account1, 100.0) >>> account.deposit(account1, 100.0) >>> account.withdraw(account1, 50.0) >>> print(account.get_balance(account1)) 150.0 ``` ## 工作原理 使用Python CFFI和CMake安装混合语言项目的扩展与第9章第6节的例子相对比,和使用Python CFFI的Python包多了两个额外的步骤: 1. 需要`setup.py`s 2. 安装目标时,CFFI所需的头文件和动态库文件,需要安装在正确的路径中,具体路径取决于所选择的Python环境 `setup.py`的结构与前面的示例几乎一致,唯一的修改是包含`install_require =['cffi']`,以确保安装示例包时,也获取并安装了所需的Python CFFI。`setup.py`脚本会自动安装`__init__.py`和`version.py`。`MANIFEST.in `中的改变不仅有`README.rst`和CMake文件,还有头文件和Fortran源文件: ```txt include README.rst CMakeLists.txt recursive-include account *.h *.f90 CMakeLists.txt ``` 这个示例中,使用Python CFFI和`setup.py`打包CMake项目时,我们会面临三个挑战: * 需要将`account.h`和`account_export.h`头文件,以及动态库复制到系统环境中Python模块的位置。 * 需要告诉`__init__.py`,在哪里可以找到这些头文件和库。第9章第6节中,我们使用环境变量解决了这些问题,不过使用Python模块时,不可能每次去都设置这些变量。 * Python方面,我们不知道动态库文件的确切名称(后缀),因为这取决于操作系统。 让我们从最后一点开始说起:不知道确切的名称,但在CMake生成构建系统时是知道的,因此我们在`interface_file_names.cfg,in`中使用生成器表达式,对占位符进行展开: ```txt [configuration] header_file_name = account.h library_file_name = $<TARGET_FILE_NAME:account> ``` 输入文件用来生成`${CMAKE_CURRENT_BINARY_DIR}/interface_file_names.cfg`: ```cmake file( GENERATE OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/interface_file_names.cfg INPUT ${CMAKE_CURRENT_SOURCE_DIR}/interface_file_names.cfg.in ) ``` 然后,将两个头文件定义为`PUBLIC_HEADER`(参见第10章),配置文件定义为`RESOURCE`: ```cmake set_target_properties(account PROPERTIES PUBLIC_HEADER "account.h;${CMAKE_CURRENT_BINARY_DIR}/account_export.h" RESOURCE "${CMAKE_CURRENT_BINARY_DIR}/interface_file_names.cfg" ) ``` 最后,将库、头文件和配置文件安装到`setup.py`定义的安装路径中: ```cmake install( TARGETS account LIBRARY DESTINATION account/lib RUNTIME DESTINATION account/lib PUBLIC_HEADER DESTINATION account/include RESOURCE DESTINATION account ) ``` 注意,我们为库和运行时都设置了指向`account/lib`的目标。这对于Windows很重要,因为动态库具有可执行入口点,因此我们必须同时指定这两个入口点。 Python包将能够找到这些文件,要使用`account/__init__.py `来完成: ```python # this interface requires the header file and library file # and these can be either provided by interface_file_names.cfg # in the same path as this file # or if this is not found then using environment variables _this_path = Path(os.path.dirname(os.path.realpath(__file__))) _cfg_file = _this_path / 'interface_file_names.cfg' if _cfg_file.exists(): config = ConfigParser() config.read(_cfg_file) header_file_name = config.get('configuration', 'header_file_name') _header_file = _this_path / 'include' / header_file_name _header_file = str(_header_file) library_file_name = config.get('configuration', 'library_file_name') _library_file = _this_path / 'lib' / library_file_name _library_file = str(_library_file) else: _header_file = os.getenv('ACCOUNT_HEADER_FILE') assert _header_file is not None _library_file = os.getenv('ACCOUNT_LIBRARY_FILE') assert _library_file is not None ``` 本例中,将找到`_cfg_file`并进行解析,`setup.py`将找到`include`下的头文件和`lib`下的库,并将它们传递给CFFI,从而构造库对象。这也是为什么,使用`lib`作为安装目标`DESTINATION`,而不使用`CMAKE_INSTALL_LIBDIR`的原因(否则可能会让`account/__init__.py `混淆)。 ## 更多信息 将包放到PyPI测试和生产实例中的后续步骤,因为有些步骤是类似的,所以可以直接参考前面的示例。