实际上属于一种代码混淆/加密的技术,你们知道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