How to read and write to hardware registers using C #?

I have absolutely no experience or knowledge regarding hardware registers and how to interact with them through code. However, my current C # project requires me to read temperatures from the chip on SMBus, and I think I will need to get my hands dirty. If you want to know, the temperature sensor is Winbond W83793G.

I have a long way to go, but I started by looking at this document on page 5: smbus.org/specs/smbb10.pdf

It seems that the first step to completing my task is to write to the following hardware registers: AX, BH, BL, CH, CL and read the return values ​​from the following: Carry, AH, AL, BL, CH, CL, DX. Using this, I can determine if the "SMBus BIOS Interface" is available. More importantly, if I can do much with C #, I can follow the rest of the documentation to ultimately read from Winbond W83793G and pull out the values ​​I want from the temperature sensors. And no, OpenHardwareMonitor does not currently support SMBus, so I cannot reference it for code.

So my main question is: what is a simple and efficient way to read and write to hardware registers using C #?

And besides, if you could provide any feedback on my specific chip reading problem, that would be a bonus for me, and I would really appreciate it!

+4
source share
3 answers

C # is a managed language running in a virtual machine. It works on various platforms. It does not have a built-in concept of hardware registers.

You will need to use low-level programming languages ​​to write code to access hardware registers.

If this code is compiled into Windows DLLs, you can then wrap this code in C # by accessing unmanaged dlls using PInvoke.

+7
source

Not supported, possibly dangerous and potentially unreasonable, but possible:

You can (or at some point) insert the built-in x86 build code in C #. An example of one way to do this :

using System; using System.Reflection; class Program { public delegate uint Ret1ArgDelegate(uint arg1); static uint PlaceHolder1(uint arg1) { return 0; } public static byte[] asmBytes = new byte[] { 0x89,0xD0, // MOV EAX,EDX 0xD1,0xC8, // ROR EAX,1 0xC3 // RET }; unsafe static void Main(string[] args) { fixed(byte* startAddress = &asmBytes[0]) // Take the address of our x86 code { // Get the FieldInfo for "_methodPtr" Type delType = typeof(Delegate); FieldInfo _methodPtr = delType.GetField("_methodPtr", BindingFlags.NonPublic | BindingFlags.Instance); // Set our delegate to our x86 code Ret1ArgDelegate del = new Ret1ArgDelegate(PlaceHolder1); _methodPtr.SetValue(del, (IntPtr)startAddress); // Enjoy uint n = (uint)0xFFFFFFFC; n = del(n); Console.WriteLine("{0:x}", n); } } } 

Another question about x86 in .NET was asked a while ago .

+4
source

You cannot write to hardware registers in a managed language such as C #. You may need to use C or assembler. The chip will probably come with devkit and instructions for programming it.

+3
source

All Articles