Discuz! BBS

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 490|回复: 0

Python 调用动态链接库 DLL

[复制链接]

254

主题

363

帖子

2431

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
2431
发表于 2024-12-1 20:04:26 | 显示全部楼层 |阅读模式
Python 调用动态库,需要以下步骤:
  1. import ctypes

  2. # 假设DLL位于当前目录下
  3. dll_path = 'example.dll'

  4. # 加载DLL
  5. example_dll = ctypes.cdll.LoadLibrary(dll_path)

  6. # 获取函数
  7. add = getattr(example_dll, 'add')

  8. # 设置函数参数类型和返回类型
  9. add.argtypes = [ctypes.c_int, ctypes.c_int]
  10. add.restype = ctypes.c_int

  11. # 调用函数
  12. result = add(3, 5)
  13. print(result)  # 输出 8
复制代码


请确保DLL文件与你的Python脚本位于同一目录中,或者提供DLL文件的完整路径。此外,DLL中的函数名称和参数类型应该与实际的DLL导出匹配,否则可能会导致错误。

  1. import os
  2. import clr

  3. script_dir = os.path.dirname(os.path.abspath(__file__))
  4. dll_path = os.path.join(script_dir, 'OpenHardwareMonitorLib.dll')

  5. clr.AddReference(dll_path)

  6. from OpenHardwareMonitor import Hardware

  7. handle = Hardware.Computer()
  8. handle.CPUEnabled = True
  9. handle.GPUEnabled = True
  10. handle.Open()
  11. cpu_temperatures = []

  12. for hardware in handle.Hardware:

  13.     hardware_type = str(hardware.HardwareType)

  14.     if 'CPU' in hardware_type.upper():

  15.         hardware.Update()

  16.         for sensor in hardware.Sensors:

  17.             if sensor.SensorType == Hardware.SensorType.Temperature:

  18.                 print("CPU温度:", sensor.Value)
  19.                 cpu_temperatures.append(sensor.Value)

  20.         if cpu_temperatures:

  21.             max_cpu_temp = max(cpu_temperatures)
  22.             print("CPU最高温度:", max_cpu_temp)

  23.     elif 'GPU' in hardware_type.upper():

  24.         hardware.Update()

  25.         for sensor in hardware.Sensors:

  26.             if sensor.SensorType == Hardware.SensorType.Temperature:

  27.                 print("GPU温度:", sensor.Value)
复制代码


如果报Python/ module ‘clr‘ has no attribute ‘AddReference‘:

首先以管理员身份运行命令行: pip uninstall clr
输入Y, 显示成功卸载;然后输入:pip install pythonnet

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|DiscuzX

GMT+8, 2025-4-16 04:54 , Processed in 0.016251 second(s), 18 queries .

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表