Mac上把python源文件编译成so文件

把python源文件编译成so文件

前言

实际上属于一种代码混淆/加密的技术,你们知道python的源文件放在那里,你们是均可以看的,不像C语言编译出来能够拿编译后的东西去运行,因此就出现了这种需求。原理至关于将python编译成c,而后再转成.so文件html

.so文件为动态连结库,能够在程序运行时动态连接,相似于windows的dll文件。python

在网上搜了一下,经常使用的有2种方法:c++

  • 经过gcc(make)来操做
  • 使用python来操做
准备工做
  • 在目录下建立__init__.pyhello.py
  • hello.py 内容为:
def hello():
    print "hello"
使用python来操做
  • 安装所需库CPython,命令以下:
pip install cython
  • 建立文件setup.py,内容以下:
from distutils.core import setup
from Cython.Build import cythonize
setup(
    ext_modules = cythonize("hello.py")
)
  • 执行setup.py文件
python setup.py build_ext --inplace
  • 在当前目录下就生成了和当前目录同名的一个目录,进入目录便可看见so文件,打开so文件可见一些乱码,达到了加密的目的
使用gcc来编译
  • 编译成c文件,完成后目录下多了hello.c
cython hello.py
  • 编译成hello.o, 完成后目录下多了hello.o
gcc -c -fPIC -I/usr/include/python2.7/ hello.c
  • 编译成so文件
gcc -undefined dynamic_lookup -shared hello.o -o hello.so
  • 部分博客写的命令没有加-undefined dynamic_lookup的参数,会报错,提示
Undefined symbols for architecture x86_64

参考https://github.com/cloudwu/skynet_sample/issues/9 加上那个参数就行了git

  • 也有说加-lstdc++参数使用c++标准库就能够的,可是我尝试了不成功,依然报一样的错误
gcc -lstdc++ -v -shared hello.o -o hello.so
验证

在so文件目录下,进入python终端,而后尝试使用一下这个模块就能够了,以下:github

>>> from hello import hello
>>> hello()
hello
参考
相关文章
相关标签/搜索