platform模块和ctypes模块

Posted angelyan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了platform模块和ctypes模块相关的知识,希望对你有一定的参考价值。

一、ctypes模块

Python 的 ctypes 要使用 C 函数,需要先将 C 编译成动态链接库的形式,即 Windows 下的 .dll 文件,或者 Linux 下的 .so 文件。先来看一下 ctypes 怎么使用 C 标准库。

Windows 系统下的 C 标准库动态链接文件为 msvcrt.dll (一般在目录 C:\Windows\System32 和 C:\Windows\SysWOW64 下分别对应 32-bit 和 64-bit,使用时不用刻意区分,Python 会选择合适的)

Linux 系统下的 C 标准库动态链接文件为 libc.so.6 (以 64-bit Ubuntu 系统为例, 在目录 /lib/x86_64-linux-gnu 下)

代码:

#例如,以下代码片段导入 C 标准库,并使用 printf 函数打印一条消息
import platform
from ctypes import *

if platform.system() == Windows:
    libc = cdll.LoadLibrary(msvcrt.dll)
    # libc = windll.LoadLibrary(‘msvcrt.dll‘)
elif platform.system() == Linux:
    libc = cdll.LoadLibrary(libc.so.6)

string=Hello ctypes!\n
libc.printf(string.encode("utf-8"))

二、platform模块

该模块用来访问平台相关属性。

常见属性和方法

# 返回平台架构
print(platform.machine())# AMD64

# 获取网络名称
print(platform.node())# DESKTOP-NMIUQ2D

# 获取系统版本
print(platform.platform())# Windows-10-10.0.17763-SP0

# 获取处理器名称
print(platform.processor())# Intel64 Family 6 Model 142 Stepping 10, GenuineIntel

# 获取系统名称
print(platform.system())# Windows

 

以上是关于platform模块和ctypes模块的主要内容,如果未能解决你的问题,请参考以下文章

ctypes 模块

使用 ctypes 创建一个 python 模块

Python ctypes 模块

python--ctypes模块:调用C函数

Mac OS X 10.9 后无法安装 PIL

聊聊Python ctypes 模块(转载)