For the purpose of learning I recently looked at an existing assembly (using Reflector) that uses Win32 WriteFile. The implementation is:
Write(IntPtr handleFile, void* bufferData, uint length){
void* buffer = bufferData
while (length > 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;
}
}
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.
Write(IntPtr handleFile, void* bufferData, uint length){
byte* buffer = (byte*)bufferData
while (length > 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;
}
}
The above code does work but still the last few lines will compile to:
buffer += (byte*)wrtn;
I do not understand why and very much would like to know why the compiler behaves in this way:
- Why does it generate the cast like this (and why is it not accepted to do this in user written code)?
- 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* ????