How to compile a Python package to a dll

Nowadays a simple solutino exists: use Nuitka compiler as described in Nuitka User Manual

Use Case 2 – Extension Module compilation
If you want to compile a single extension module, all you have to do is this:

 python -m nuitka --module 

The resulting file can then be used instead of

You need to compile for each platform you want to support and write some initialization code to import so/pyd file ~~appropriate for given platform/python version etc.~~

[EDIT 2021-12]: Actually in python 3 the proper so/dll is determined automatically based on the file name (if it includes python version and platform – can’t find PEP for this feature at the moment but Nuitka creates proper names for compiled modules). So for python 2.7 the library name would be something.pyd or whereas for python 3 this would change to something.cp36-win32.pyd or (for 32bit python 3.6 on x86).

The result is not DLL as requested but Python-native compiled binary format (it is not bytecode like in pyc files; the so/pyd format cannot be easily decompiled – Nuitka compiles to machine code through C++ translation)

EDIT [2020-01]: The compiled module is prone to evaluation methods using python standard mechanisms – e.g. it can be imported as any other module and get its methods listed etc. To secure implementation from being exposed that way there is more work to be done than just compiling to a binary module.

Leave a Comment