来自不同平台(Windows,Linux或OS X)的Python加载库



我是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

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

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

最新更新