StuuTooTo:从C++代码构建共享库,然后构建链接到共享库的Cython包装器

2024-10-02 20:36:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我们有一组C++类的文件,我们使用Cython将它们包到Python。我们使用setuptools构建Cython扩展。这一切都很好,我们遵循以下指南: http://cython.readthedocs.io/en/latest/src/userguide/wrapping_CPlusPlus.html

我们基本上是这样做的

from distutils.core import setup
from Cython.Build import cythonize

setup(ext_modules = cythonize(
           "rect.pyx",                 # our Cython source
           sources=["Rectangle.cpp"],  # additional source file(s)
           language="c++",             # generate C++ code
      ))

我们不喜欢这样,我们必须重新编译所有内容,即使只有Cython部分发生了更改,rect.pyx在本例中。事实上,我们从不接触.cpp文件,而是经常更改.pyx文件

我们希望将.cpp文件分别编译成静态或共享库,然后独立构建.pyx文件,该文件链接到从.cpp文件生成的库。使用makecmake这一切都很容易,但我们需要一个只使用setuptools的纯Python解决方案。模拟代码如下所示:

from distutils.core import setup
from Cython.Build import cythonize

class CppLibary:
    # somehow get that to work

# this should only recompile cpplib when source files changed
cpplib = CppLibary('cpplib',
                   sources=["Rectangle.cpp"], # put static cpp code here
                   include_dirs=["include"])

setup(ext_modules = cythonize(
           "rect.pyx",                 # our Cython source
           libraries=[cpplib],         # link to cpplib
           language="c++",             # generate C++ code
      ))

Tags: 文件fromcorerectimportsourcesetupcode
1条回答
网友
1楼 · 发布于 2024-10-02 20:36:09

setup的一个看似未记录的功能可以做到这一点,例如:

import os

from setuptools import setup
from Cython.Build import cythonize

ext_lib_path = 'rectangle'
include_dir = os.path.join(ext_lib_path, 'include')

sources = ['Rectangle.cpp']

# Use as macros = [('<DEFINITION>', '<VALUE>')]
# where value can be None
macros = None

ext_libraries = [['rectangle', {
               'sources': [os.path.join(ext_lib_path, src) for src in sources],
               'include_dirs': [include_dir],
               'macros': macros,
               }
]]

extensions = [Extension("rect",
              sources=["rect.pyx"],
              language="c++",
              include_dirs=[include_dir],
              libraries=['rectangle'],
)]

setup(ext_modules=cythonize(extensions),
      libraries=ext_libraries)

libraries参数构建在目录rectangle中找到的外部库,在它和扩展之间使用include目录rectangle/include公共

还将导入从distutils切换到setuptools,该导入已被弃用,现在是setuptools的一部分

我还没有看到关于这个论点的任何文档,但看到它在其他项目中使用过

这是未经测试的,如果不起作用,请提供样本文件进行测试

相关问题 更多 >