Zhao Yu
Zhao Yu

Reputation: 63

Python load library from different platform (Windows, Linux or OS X)

I am a Python beginner from C language. Now I have plan to implement a cross platform project with Python + C library (ctypes) running on Windows, Linux and OS X and I have win32.dll, win64.dll, mac_osx.so linux.so files ready.

How to load them by a single Python (.py) file?

My idea is to use Python OS or platform module to check environment, like this (sorry this is not the real Python program):

if Windows and X86 then load win32.dll
else if Windows and X64 then load win64.dll
else if OSX then load osx.so
else if Linux then load linux.so

Are there any simple and clear way to do this work?

Upvotes: 6

Views: 8537

Answers (1)

Juan Antonio Orozco
Juan Antonio Orozco

Reputation: 750

you can use the ctypes.cdll module to load the DLL/SO/DYLIB and the platform module to detect the system you are running on.

a minimal working example would be like this:

import platform
from ctypes import *

# get the right filename
if platform.uname()[0] == "Windows":
    name = "win.dll"
elif platform.uname()[0] == "Linux":
    name = "linux.so"
else:
    name = "osx.dylib"
    
# load the library
lib = cdll.LoadLibrary(name)

please note that you will need an 64 bit python interpreter to load 64 bit libraries and an 32 bit python interpreter to load 32 bit libraries

Upvotes: 9

Related Questions