Low level development with C#?

This question may be strange, but I'm definitely curious. So I come from a low level background (4 years of C/3 of C++) and I'm learning C# at the moment because…well…that's all that anyone in my city uses, ergo if I want a job, C# it is. I am asking this because I am extremely bored with writing GUI apps, I find I'm not learning much about the actual language or what it is capable of, all I'm really learning is "Here's how awesome WPF is, and heres how you drag and drop a combo-box and change the markup" etc.

What I'm really interested in and I find I have a lot more fun with and frankly learn more from is lower level development, where I'm actually talking to the OS, and doing something a bit more…engaging I suppose. Is there any way of doing this in C#? I mean I know you can sort of read the IL that the compiler spits out and such, but I'm not talking about that, I want to write C# code that does low level stuff, plain and simple (Think Win32 with C). Any input is appreciated, even if it's "Nope, can't do it, you're a moron". Thanks!

by Trevor266 via /r/csharp

2 Replies to “Low level development with C#?”

  1. Add the word “unsafe” before a method and enjoy pointers once more.

    Add the IL Support extension through the menu in Visual Studio to gain access to writing methods in CIL/bytecode, which will allow you to almost completely ignore strong typing.

    Using C dll’s you can export your favorite compiler intrinsics and assembly code, then use reflection once at runtime to get a pointer to the functions after loading the library and off you go! CIL/MSIL is much more powerful than Java bytecode.

    You will find that the memory layout of C++, Java, and C# objects is largely the same. Follow the pointer stored at the address of an object to get to its method table (vtable). For fun, compile methods at runtime, get their function pointers, and then gorilla patch the vtable with your own implementation.

  2. Structs are great too. I had fun once stack-allocating a string in .NET, then passing a pointer into my stack to another thread to call ToString() and display it.

    Here is the struct definition for my stack-allocated string that I used:

    unsafe struct MyCrazyString
    IntPtr _syncBlock;
    IntPtr _methodTable;
    char[12] _chars;

    Fill the first eleven chars in _chars with “Hello World”, then write typeof(string).RuntimeTypeHandle.Value into _methodTable. Then take a pointer to the local variable holding the struct, pass it into an IL method that returns a pointer to string, and you can pass this around and it will remain perfectly valid as a string until your local goes out of scope (at which point, outstanding pointers will be invalid).

Leave a Reply