简体   繁体   中英

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?

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"
if 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM