Search code examples
c#sensorsnvapiopenhardwaremonitor

How to use Libre Hardware Monitor library to read GPU sensors


I'm write a simple C# application using Libre Hardware Monitor library. Everything works fine except gpu sensors. If I'm set GPUEnabled to "true" I got following message:

Managed Debugging Assistant 'PInvokeStackImbalance' : 
'A call to PInvoke function'OpenHardwareMonitorLib!OpenHardwareMonitor.Hardware.
Nvidia.NVAPI+NvAPI_GetInterfaceVersionStringDelegate::Invoke' has unbalanced the stack. 
This is likely because the managed PInvoke signature does not match the unmanaged target
signature. Check that the calling convention and parameters of 
the PInvoke signature match the target unmanaged signature.'

in the NVAPI.cs 335. line

public static NvStatus NvAPI_GetInterfaceVersionString(out string version) {
      StringBuilder builder = new StringBuilder(SHORT_STRING_MAX);
      NvStatus status;
      if (_NvAPI_GetInterfaceVersionString != null)
/*335*/ status = _NvAPI_GetInterfaceVersionString(builder);
      else
        status = NvStatus.FUNCTION_NOT_FOUND;
      version = builder.ToString();
      return status;
    }

With Libre Hardware Monitor everything works fine.
GPU: ASUS-ROG-STRIX-RTX2080-O8G-GAMING
My code (mainly from here):

Computer thisPC;

public EMSSettings()
{
    InitializeComponent();

    thisPC = new Computer()
    {
        GPUEnabled = true
    };

    thisPC.Open();
}

private void timer1_Tick(object sender, EventArgs e)
{

    String temp = "";

    foreach (var hardwareItem in thisPC.Hardware)
    {
        if (hardwareItem.HardwareType == HardwareType.CPU || true)
        {
            hardwareItem.Update();
            foreach (IHardware subHardware in hardwareItem.SubHardware)
                subHardware.Update();

            foreach (var sensor in hardwareItem.Sensors)
            {
                if (sensor.SensorType == SensorType.Temperature || true)
                {

                    temp += String.Format("{0} Temperature = {1}\r\n", sensor.Name, sensor.Value.HasValue ? sensor.Value.Value.ToString() : "no value");

                }
            }
        }
    }

    textBox1.Text = temp;

}

Thanks for all the answers


Solution

  • The answer is here: https://stackoverflow.com/a/39203588/9355850
    Add [UnmanagedFunctionPointer(CallingConvention.Cdecl)] before every delegate.