Eric Smith Eric Smith - 1 year ago 81
Python Question

How can I make a Python Wheel from an existing native library?

Suppose I have a native shared library (.dll or .so), built independently of any Python mechanism, and a Python module using ctypes to interface to the library. Is there a way that I can build those into a .whl package? If so, how?

Assuming this is possible, I think I'd need the wheel package installed and to use

python bdist_wheel
but what would my need to look like?

I'd like to do this so I can upload Wheels for various platforms into a private package index and be able to pip install the appropriate one for the platform I'm on.

Answer Source

Here is a way. For an example, this uses libeay32.dll to expose an md5 package.

The project structure is:


The is:

from setuptools import setup, Distribution

class BinaryDistribution(Distribution):
    def is_pure(self):
        return False

    description='MD5 Library',
        'md5': ['libeay32.dll'],

A couple of things to note:

  1. The DLL is listed as package data so that it will be included in the wheel.
  2. A custom distclass is used that indicates this wheel is not "pure", and since the wheel being built on Windows, that this is a win32 wheel.

The Python ctypes code can load the DLL relative to itself (this code is in __init.py__):

lib_path = os.path.join(os.path.dirname(__file__), 'libeay32.dll')
lib = CDLL(lib_path)

After having installed 'wheel' with pip, I can run python bdist_wheel to produce dist\md5-1.0-cp34-none-win32.whl. I happen to be using cpython 3.4, but if you want a universal wheel, you can add a setup.cfg like this one.

Now I can create and activate a new virtual environment, pip install md5-1.0-cp34-none-win32.whl, and use my package:

>>> import md5
>>> md5.digest('hello')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download