|
Python 调用动态库,需要以下步骤:
- import ctypes
-
- # 假设DLL位于当前目录下
- dll_path = 'example.dll'
-
- # 加载DLL
- example_dll = ctypes.cdll.LoadLibrary(dll_path)
-
- # 获取函数
- add = getattr(example_dll, 'add')
-
- # 设置函数参数类型和返回类型
- add.argtypes = [ctypes.c_int, ctypes.c_int]
- add.restype = ctypes.c_int
-
- # 调用函数
- result = add(3, 5)
- print(result) # 输出 8
复制代码
请确保DLL文件与你的Python脚本位于同一目录中,或者提供DLL文件的完整路径。此外,DLL中的函数名称和参数类型应该与实际的DLL导出匹配,否则可能会导致错误。
- import os
- import clr
- script_dir = os.path.dirname(os.path.abspath(__file__))
- dll_path = os.path.join(script_dir, 'OpenHardwareMonitorLib.dll')
- clr.AddReference(dll_path)
- from OpenHardwareMonitor import Hardware
- handle = Hardware.Computer()
- handle.CPUEnabled = True
- handle.GPUEnabled = True
- handle.Open()
- cpu_temperatures = []
- for hardware in handle.Hardware:
- hardware_type = str(hardware.HardwareType)
- if 'CPU' in hardware_type.upper():
- hardware.Update()
- for sensor in hardware.Sensors:
- if sensor.SensorType == Hardware.SensorType.Temperature:
- print("CPU温度:", sensor.Value)
- cpu_temperatures.append(sensor.Value)
- if cpu_temperatures:
- max_cpu_temp = max(cpu_temperatures)
- print("CPU最高温度:", max_cpu_temp)
- elif 'GPU' in hardware_type.upper():
- hardware.Update()
- for sensor in hardware.Sensors:
- if sensor.SensorType == Hardware.SensorType.Temperature:
- print("GPU温度:", sensor.Value)
复制代码
如果报Python/ module ‘clr‘ has no attribute ‘AddReference‘:
首先以管理员身份运行命令行: pip uninstall clr
输入Y, 显示成功卸载;然后输入:pip install pythonnet
|
|