我可以使用distutils创建静态Cython库吗?
我想用distutils来构建一个静态的Cython库。我并不在乎它是否能作为真正的Python扩展模块被导入。我只想编译代码,然后把对象放到一个静态库里。创建动态库的代码非常简单,
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup(
cmdclass = {'build_ext':build_ext},
ext_modules = [Extension("test",["test.pyx"])]
)
那么有没有简单的方法可以让它变成静态库呢?
3 个回答
0
假设你的setup.py文件里有sources
、include_dirs
和build_dir
这几个部分,下面就是如何构建一个静态库的方法。
from distutils.ccompiler import new_compiler
from sysconfig import get_paths
import os
project_name = "slimey_project"
source = ['source1.c']
include_dirs = ['include']
build_dir = os.path.join(os.path.dirname(__file__), 'build')
class StaticLib(Command):
description = 'build static lib'
user_options = [] # do not remove, needs to be stubbed out!
python_info = get_paths()
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
# Create compiler with default options
c = new_compiler()
# Optionally add include directories etc.
for d in include_dirs:
c.add_include_dir(d)
c.add_include_dir(self.python_info['include'])
# Compile into .o files
objects = c.compile(sources)
# Create static or shared library
c.create_static_lib(objects, project_name, output_dir=build_dir)
来源:https://gist.github.com/udnaan/d549950a33fd82d13f9e6ba4aae82964
1
顺便说一下,这个方法是通过 numpy distutils
实现的,但显然它的简单程度和可能的可移植性都比不上原始的共享库代码。
from Cython.Compiler.Main import compile
from numpy.distutils.misc_util import Configuration
compile('test.pyx')
config = Configuration(...)
config.add_installed_library('test',
['test.c'],
'test',
{'include_dirs':[get_python_inc()]})
2
Distutils的功能很有限,而且不适合用来做静态构建。我建议你使用其他工具来编译项目中的静态库部分。
如果你的需求是从其他C代码中调用Cython代码,那么你需要在Cython代码中使用public
或api
声明,同时配合你用cdef
声明的函数和变量。这样,Cython就能让这些声明的对象可以被外部的C代码调用,并且它会为你生成一个与.c
文件一起的.h
文件。