As everyone knows,Python is an interpreted language. If you don’t want to show your code to others, you can compile Python source code to generate a .pyd library file (for Windows) or a .so library file (for Linux).

Windows python to .pyd

Suppose you now have a test.py

1
2
3
# test.py
def add(a, b):
return a+b

Now you want to compile the test.py into a pyd file. Create a new setup.py as follows:

1
2
3
4
5
# setup.py
from distutils.core import setup
from Cython.Build import cythonize

setup(name='test', ext_modules=cythonize('test.py'))
1
python setup.py build

A build folder will be created with the generated .pyd file in it. Copy the pyd file to the current directory (personal habit) and call .pyd as follows:

1
2
3
4
5
from test import add

if __name__ == '__main__':
a, b = 1, 1
print(add(a, b))

Or compile with python setup.py build_ext --inplace, so that the .pyd file is generated directly in the current directory and then called as described above.

Linux python to .so

Similarly to windows generating .pyd file, also take test.py as an example,build setup.py file

1
2
3
4
5
# setup.py
from distutils.core import setup
from Cython.Build import cythonize

setup(ext_modules = cythonize(['test.py']))
1
python3 setup.py build_ext --inplace

call .so file

1
2
3
4
import ctypes

ll = ctypes.cdll.LoadLibrary
demo = ll("test.so")

Linux C++ to .so

1
gcc -shared -f PIC test.c -o test.so