python - 扩展 setuptools 扩展以在 setup.py 中使用 CMake?

标签 python c++ cmake setuptools packaging

我正在编写一个链接 C++ 库的 Python 扩展,并且我正在使用 cmake 来帮助构建过程。这意味着现在,我知道如何捆绑它的唯一方法是,我必须先用 cmake 编译它们,然后才能运行 setup.py bdist_wheel。一定有更好的办法。

我想知道是否可以(或任何人尝试过)调用 CMake 作为 setup.py ext_modules 构建过程的一部分?我猜有一种方法可以创建某些东西的子类,但我不确定在哪里看。

我使用 CMake 是因为它让我可以更好地控制构建 c 和 c++ 库扩展,并完全按照我的需要进行复杂的构建步骤。另外,我可以使用 findPythonLibs.cmake 中的 PYTHON_ADD_MODULE() 命令直接使用 cmake 轻松构建 Python 扩展。我只希望这只是一步。

最佳答案

您基本上需要做的是覆盖 setup.py 中的 build_ext 命令类并将其注册到命令类中。在您自定义的 build_ext 实现中,配置并调用 cmake 来配置然后构建扩展模块。不幸的是,官方文档对于如何实现自定义 distutils 命令相当简洁(参见 Extending Distutils );我发现直接研究命令代码更有帮助。例如,这里是 build_ext command 的源代码.

示例项目

我准备了一个简单的项目,由一个 C 扩展 foo 和一个 python 模块 spam.eggs 组成:

so-42585210/
├── spam
│   ├── __init__.py  # empty
│   ├── eggs.py
│   ├── foo.c
│   └── foo.h
├── CMakeLists.txt
└── setup.py

用于测试设置的文件

这些只是我为测试设置脚本而编写的一些简单 stub 。

spam/eggs.py(仅用于测试库调用):

from ctypes import cdll
import pathlib


def wrap_bar():
    foo = cdll.LoadLibrary(str(pathlib.Path(__file__).with_name('libfoo.dylib')))
    return foo.bar()

spam/foo.c:

#include "foo.h"

int bar() {
    return 42;
}

spam/foo.h:

#ifndef __FOO_H__
#define __FOO_H__

int bar();

#endif

CMakeLists.txt:

cmake_minimum_required(VERSION 3.10.1)
project(spam)
set(src "spam")
set(foo_src "spam/foo.c")
add_library(foo SHARED ${foo_src})

设置脚本

这就是魔法发生的地方。当然,还有很大的改进空间 - 如果需要,您可以将其他选项传递给 CMakeExtension 类(有关扩展的更多信息,请参阅 Building C and C++ Extensions ),使 CMake 选项可配置通过 setup.cfg 覆盖方法 initialize_optionsfinalize_options 等。

import os
import pathlib

from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext as build_ext_orig


class CMakeExtension(Extension):

    def __init__(self, name):
        # don't invoke the original build_ext for this special extension
        super().__init__(name, sources=[])


class build_ext(build_ext_orig):

    def run(self):
        for ext in self.extensions:
            self.build_cmake(ext)
        super().run()

    def build_cmake(self, ext):
        cwd = pathlib.Path().absolute()

        # these dirs will be created in build_py, so if you don't have
        # any python sources to bundle, the dirs will be missing
        build_temp = pathlib.Path(self.build_temp)
        build_temp.mkdir(parents=True, exist_ok=True)
        extdir = pathlib.Path(self.get_ext_fullpath(ext.name))
        extdir.mkdir(parents=True, exist_ok=True)

        # example of cmake args
        config = 'Debug' if self.debug else 'Release'
        cmake_args = [
            '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=' + str(extdir.parent.absolute()),
            '-DCMAKE_BUILD_TYPE=' + config
        ]

        # example of build args
        build_args = [
            '--config', config,
            '--', '-j4'
        ]

        os.chdir(str(build_temp))
        self.spawn(['cmake', str(cwd)] + cmake_args)
        if not self.dry_run:
            self.spawn(['cmake', '--build', '.'] + build_args)
        # Troubleshooting: if fail on line above then delete all possible 
        # temporary CMake files including "CMakeCache.txt" in top level dir.
        os.chdir(str(cwd))


setup(
    name='spam',
    version='0.1',
    packages=['spam'],
    ext_modules=[CMakeExtension('spam/foo')],
    cmdclass={
        'build_ext': build_ext,
    }
)

测试

构建项目的轮子,安装它。测试库是否安装:

$ pip show -f spam
Name: spam
Version: 0.1
Summary: UNKNOWN
Home-page: UNKNOWN
Author: UNKNOWN
Author-email: UNKNOWN
License: UNKNOWN
Location: /Users/hoefling/.virtualenvs/stackoverflow/lib/python3.6/site-packages
Requires: 
Files:
  spam-0.1.dist-info/DESCRIPTION.rst
  spam-0.1.dist-info/INSTALLER
  spam-0.1.dist-info/METADATA
  spam-0.1.dist-info/RECORD
  spam-0.1.dist-info/WHEEL
  spam-0.1.dist-info/metadata.json
  spam-0.1.dist-info/top_level.txt
  spam/__init__.py
  spam/__pycache__/__init__.cpython-36.pyc
  spam/__pycache__/eggs.cpython-36.pyc
  spam/eggs.py
  <b>spam/libfoo.dylib</b>

spam.eggs 模块运行包装函数:

$ python -c "from spam import eggs; print(eggs.wrap_bar())"
42

关于python - 扩展 setuptools 扩展以在 setup.py 中使用 CMake?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42585210/

相关文章:

c++ - 使用 CMake 和 GCC 在 Mac 上构建静态库?

python - 当 ['href' ] 元素是超链接时如何提取 href

python - 在Python中打印某些JSON数据

python - 需要有关discord.py bot的建议

c++ - 如何在 CLion 中运行 SFML,错误 undefined reference ?

c# - CMake CSharp 引用 nuget 包

Python元组字典加法

c++ - 仅当使用 opengl 3.2 上下文或更高版本时,glVertexAttribPointer 和 glDrawArrays 的 GL_ERROR == 1282

c++ - 标准库 `emplace` 函数是否使用 `std::in_place` 标签

c++ - C++ 中的内置数据类型与用户定义的数据类型