Note that there are some explanatory texts on larger screens.

plurals
  1. POpointer arithmetic and the C# compiler
    text
    copied!<p>For the purpose of learning I recently looked at an existing assembly (using Reflector) that uses Win32 WriteFile. The implementation is:</p> <pre><code>Write(IntPtr handleFile, void* bufferData, uint length){ void* buffer = bufferData while (length &gt; 0) { uint wrtn; if (!WriteFile(handle, buffer, len, out wrtn, IntPtr.Zero)) { // Do some error handling } // This does not compile, because of the cast but also simply because void* does not have += operators (it is unknown size). buffer += (void*)wrtn; len -= wrtn; } </code></pre> <p>}</p> <p>It is actually the last 2 lines that are problematic... For one, the compiler complains that you cannot cast uint to void*. Additionally, it is just not possible to use += or even + on void* because it is not of known size.</p> <pre><code>Write(IntPtr handleFile, void* bufferData, uint length){ byte* buffer = (byte*)bufferData while (length &gt; 0) { uint wrtn; if (!WriteFile(handle, (void*)buffer, len, out wrtn, IntPtr.Zero)) { // Do some error handling } // This works! I can add to a byte* buffer = buffer + wrtn; // I could also have used buffer += wrtn len -= wrtn; } } </code></pre> <p>The above code does work but still the last few lines will compile to:</p> <pre><code>buffer += (byte*)wrtn; </code></pre> <p>I do not understand why and very much would like to know why the compiler behaves in this way:</p> <ol> <li>Why does it generate the cast like this (and why is it not accepted to do this in user written code)?</li> <li>What is up with the += operators on void* in the first example? What original code code have generated buffer += (void*)wrtn where buffer is also void* ????</li> </ol>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload