【问题标题】:Pass numpy's include dir to Cmake from Setuptools从 Setuptools 将 numpy 的包含目录传递给 Cmake
【发布时间】:2023-12-09 04:44:01
【问题描述】:

我有一个 C++ 库,我已经使用 Pybind11 成功地将它暴露给了 python。

CmakeLists.txt 文件中,我添加了这样的 numpy 包含:

include_directories("C:\\Python37\\Lib\\site-packages\\numpy\\core\\include")

这可行,但不可取。我想从我的setup.py 文件中传递 numpy 包含目录。

我的setup.py 文件看起来很像this one

import os
import re
import sys
import sysconfig
import platform
import subprocess

from distutils.version import LooseVersion
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext


class CMakeExtension(Extension):
    def __init__(self, name, sourcedir=''):
        Extension.__init__(self, name, sources=[])
        self.sourcedir = os.path.abspath(sourcedir)


class CMakeBuild(build_ext):
    def run(self):
        try:
            out = subprocess.check_output(['cmake', '--version'])
        except OSError:
            raise RuntimeError(
                "CMake must be installed to build the following extensions: " +
                ", ".join(e.name for e in self.extensions))

        if platform.system() == "Windows":
            cmake_version = LooseVersion(re.search(r'version\s*([\d.]+)',
                                         out.decode()).group(1))
            if cmake_version < '3.1.0':
                raise RuntimeError("CMake >= 3.1.0 is required on Windows")

        for ext in self.extensions:
            self.build_extension(ext)

    def build_extension(self, ext):
        extdir = os.path.abspath(
            os.path.dirname(self.get_ext_fullpath(ext.name)))
        cmake_args = ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=' + extdir,
                      '-DPYTHON_EXECUTABLE=' + sys.executable]

        cfg = 'Debug' if self.debug else 'Release'
        build_args = ['--config', cfg]

        if platform.system() == "Windows":
            cmake_args += ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_{}={}'.format(
                cfg.upper(),
                extdir)]
            if sys.maxsize > 2**32:
                cmake_args += ['-A', 'x64']
            build_args += ['--', '/m']
        else:
            cmake_args += ['-DCMAKE_BUILD_TYPE=' + cfg]
            build_args += ['--', '-j2']

        env = os.environ.copy()
        env['CXXFLAGS'] = '{} -DVERSION_INFO=\\"{}\\"'.format(
            env.get('CXXFLAGS', ''),
            self.distribution.get_version())
        if not os.path.exists(self.build_temp):
            os.makedirs(self.build_temp)
        subprocess.check_call(['cmake', ext.sourcedir] + cmake_args,
                              cwd=self.build_temp, env=env)
        subprocess.check_call(['cmake', '--build', '.'] + build_args,
                              cwd=self.build_temp)
        print()  # Add an empty line for cleaner output

setup(
    name='python_cpp_example',
    version='0.1',
    author='Benjamin Jack',
    author_email='benjamin.r.jack@gmail.com',
    description='A hybrid Python/C++ test project',
    long_description='',
    # add extension module
    ext_modules=[CMakeExtension('python_cpp_example')],
    # add custom build_ext command
    cmdclass=dict(build_ext=CMakeBuild),
    zip_safe=False,
)

看了this之类的SO问题后,我知道您可以使用numpy.get_include()获取numpy包含目录。

但是,使用 ext.include_dirs.append(numpy.get_include()) 这一行将包含目录添加到函数 build_extension 内的路径似乎没有效果。

我想知道如何正确传递包含目录。

【问题讨论】:

    标签: c++ python-3.x cmake setuptools pybind11


    【解决方案1】:

    您的 cmake 构建是使用错误的 numpy 路径还是根本找不到 numpy?如果路径错误,您可以尝试预先添加而不是添加numpy.get_include()

    ext.include_dirs.insert(0,numpy.get_include())
    

    【讨论】:

    • 很奇怪,这看起来像是解决方案。我会检查一个不同的 python 发行版,如果它有效,我会接受解决方案
    • 这个工作的原因:cmake 正在检查一个包的所有 INCLUDE_DIRS 并在找到它后停止。这与 unix PATH 变量使用的层次结构相同。