Calling unmanaged Code from C# -


with inspiration openhardwaremonitor project have made myself nice gadget monitor cpu , gpu metrics temperature, load, etc.

it works fine running in pinvokestackimbalance warning when calling nvidia driver methods , don't think wise ignore them.

however after weeks of experimentation (with nvidia documentaion in hand) still can't figure out how define , use drivers structs , methods in such way vs 2015 happy - strange because there no warnings in openhardwaremonitor project despite using exact same code.

hopefully here can point me in right direction.

[dllimport("nvapi.dll", callingconvention = callingconvention.cdecl, preservesig = true)] private static extern intptr nvapi_queryinterface(uint id);  private delegate nvstatus nvapi_enumphysicalgpusdelegate([out] nvphysicalgpuhandle[] gpuhandles, out int gpucount); private static readonly nvapi_enumphysicalgpusdelegate nvapi_enumphysicalgpus;  nvapi_enumphysicalgpus = marshal.getdelegateforfunctionpointer(nvapi_queryinterface(0xe5ac921f), typeof(nvapi_enumphysicalgpusdelegate)) nvapi_enumphysicalgpusdelegate;  status = nvapi_enumphysicalgpus != null ? nvapi_enumphysicalgpus(physicalgpuhandles, out physicalgpuhandlescount) : nvstatus.function_not_found; // warning thrown here 

first, functions c-style, not c++. fortunate, since interoping c++ directly c# huge pain (you'd want use c++/cli in case).

native interop not easy. need understand owns memory, how allocate , deallocate it, , need pay lot of attention whether you're running 32-bit or 64-bit.

at first glance, you're missing calling convention on delegate, default stdcall. however, defined in nvapi (and reasonable interop libraries), supposed use cdecl:

[unmanagedfunctionpointer(callingconvention.cdecl)]  private delegate nvstatus nvapi_enumphysicalgpusdelegate([out] nvphysicalgpuhandle[] gpuhandles, out int gpucount); 

the tricky thing cdecl , stdcall both similar (the arguments passed on stack right-to-left, return value goes in eax if integer or poitner etc.), except in cdecl, caller responsible clearing stack, while in stdcall, it's callee's job. means p/invoking stdcall instead of cdecl work (the .net runtime notices stack imbalance , fixes it), produce warning.

if doesn't solve problem, pay attention bitness. try using 32-bit library 32-bit .net application.


Comments

Popular posts from this blog

amazon web services - S3 Pre-signed POST validate file type? -

c# - Check Keyboard Input Winforms -