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
參考
相關文章
相關標籤/搜索