【问题标题】:Python load library from different platform (Windows, Linux or OS X)来自不同平台(Windows、Linux 或 OS X)的 Python 加载库
【发布时间】:2018-10-14 13:47:55
【问题描述】:

我是 C 语言的 Python 初学者。现在我计划使用在 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

有没有简单明了的方法来完成这项工作?

【问题讨论】:

  • mac_osx.so?不是 .dylib?

标签: python ctype


【解决方案1】:

您可以使用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 位库

【讨论】:

    猜你喜欢
    • 2017-07-30
    • 2014-10-25
    • 2013-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多