Python 从不同平台加载库(Windows、Linux 或 OS X)

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

我是Python C语言初学者。现在我计划在 Windows、Linux 和 OS X 上使用 Python + C 库 (ctypes) 运行 实施一个跨平台项目,我有 win32.dll、win64.dll、mac_osx.so linux.so 文件准备就绪。

如何通过单个 Python (.py) 文件加载它们?

我的想法是使用 Python OS 或平台模块来检查环境,像这样(抱歉这不是真正的 Python 程序):

  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

有什么简单明了的方法来做这个工作吗?

您可以使用 ctypes.cdll 模块加载 DLL/SO/DYLIB 和 platform 模块来检测您 运行 所在的系统。

一个最小的工作示例是这样的:

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)

请注意,您需要一个 64 位 python 解释器来加载 64 位库和一个 32 位 python 解释器来加载 32 位库