如何在python的setup.py中调用cmake构建python库的插件

Sunday, December 3, 2023
本文共127字
1分钟阅读时长

⚠️本文是作者P3troL1er原创,首发于https://peterliuzhi.top/posts/%E5%A6%82%E4%BD%95%E5%9C%A8python%E7%9A%84setup.py%E4%B8%AD%E8%B0%83%E7%94%A8cmake%E6%9E%84%E5%BB%BApython%E5%BA%93%E7%9A%84%E6%8F%92%E4%BB%B6/。商业转载请联系作者获得授权,非商业转载请注明出处!

Without some goals and some efforts to reach it, no man can live. — John Dewey

首先需要编写好CMakeList.txt,然后编写setup.py如下:

# setup.py

from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
import sys
import os
import setuptools

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

class CMakeBuild(build_ext):
    def run(self):
        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]

        build_args = []
        os.makedirs("build", exist_ok=True)
        os.system(f"cd build && cmake .. {' '.join(cmake_args)} && cmake --build .")

setup(
    name='mylib',
    version='0.1',
    ext_modules=[CMakeExtension('c_lib')],
    cmdclass={'build_ext': CMakeBuild},
    zip_safe=False,
)