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就可以。

准备工作

项目将使用如下的目录结构:

  1. .
  2. ├── account
  3. ├── account.h
  4. ├── CMakeLists.txt
  5. ├── implementation
  6. └── fortran_implementation.f90
  7. ├── __init__.py
  8. ├── interface_file_names.cfg.in
  9. ├── test.py
  10. └── version.py
  11. ├── CMakeLists.txt
  12. ├── MANIFEST.in
  13. ├── README.rst
  14. └── setup.py

CMakeLists.txt文件和account下面的所有源文件(account/CMakeLists.txt除外)与第9章中的使用方式相同。README.rst文件与前面的示例相同。setup.py脚本比上一个示例多了一行(包含install_require =['cffi']的那一行):

# ... 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模块和包一起安装,并包含以下内容:

include README.rst CMakeLists.txt
recursive-include account *.h *.f90 CMakeLists.txt

account子目录下,我们看到两个新文件。一个version.py文件,其为setup.py保存项目的版本信息:

__version__ = '0.0.0'

子目录还包含interface_file_names.cfg.in文件:

[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 )


<br />安装目标和附加文件准备好之后,就可以测试安装了。为此,会在某处创建一个新目录,我们将在那里测试安装。

2. 
新创建的目录中,我们从本地路径运行pipenv install。调整本地路径,指向`setup.py`脚本保存的目录:
```shell
$ pipenv install /path/to/fortran-example
  1. 现在在Pipenv环境中生成一个Python shell:
    $ pipenv run python
    
  1. 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




<a name="b3fbd195"></a>
## 工作原理

使用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源文件:

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`中使用生成器表达式,对占位符进行展开:

[configuration] header_file_name = account.h library_file_name = $


输入文件用来生成`${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

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定义的安装路径中:

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来完成:

# 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测试和生产实例中的后续步骤,因为有些步骤是类似的,所以可以直接参考前面的示例。