网络编程
位置:首页>> 网络编程>> Python编程>> Cython编译python为so 代码加密示例

Cython编译python为so 代码加密示例

作者:nxeexn  发布时间:2023-01-22 13:16:48 

标签:Cython,python,so

1. 编译出来的so比网上流传的其他方法小很多。

2. language_level  是python的主版本号,如果python版本是2.x,目前的版本Cython需要人工指定language_level.

3. python setup.py build_ext --inplace  执行脚本

4. 以下是代码片段


from distutils.core import Extension, setup

from Cython.Build import cythonize
from Cython.Compiler import Options

# __file__ 含有魔术变量的应当排除,Cython虽有个编译参数,但只能设置静态。
exclude_so = ['__init__.py', "mixins.py"]
sources = ['core', 'libs']

extensions = []
for source in sources:
 for dirpath, foldernames, filenames in os.walk(source):
   for filename in filter(lambda x: re.match(r'.*[.]py$', x), filenames):
     file_path = os.path.join(dirpath, filename)
     if filename not in exclude_so:
       extensions.append(
           Extension(file_path[:-3].replace('/', '.'), [file_path], extra_compile_args = ["-Os", "-g0"],
                extra_link_args = ["-Wl,--strip-all"]))

Options.docstrings = False
compiler_directives = {'optimize.unpack_method_calls': False}
setup(
   # cythonize的exclude全路径匹配,不灵活,不如在上一步排除。
   ext_modules = cythonize(extensions, exclude = None, nthreads = 20, quiet = True, build_dir = './build',
               language_level = 2 或者3 , compiler_directives = compiler_directives))

来源:https://blog.csdn.net/nxeexn/article/details/83996248

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com