實際上屬於一種代碼混淆/加密的技術,你們知道python的源文件放在那裏,你們是均可以看的,不像C語言編譯出來能夠拿編譯後的東西去運行,因此就出現了這種需求。原理至關於將python編譯成c,而後再轉成.so文件html
.so文件爲動態連結庫,能夠在程序運行時動態連接,相似於windows的dll文件。python
在網上搜了一下,經常使用的有2種方法:c++
__init__.py
和hello.py
hello.py
內容爲:def hello(): print "hello"
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
hello.c
cython hello.py
hello.o
, 完成後目錄下多了hello.o
gcc -c -fPIC -I/usr/include/python2.7/ hello.c
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