Is IntPtr.Zero equivalent to zero?

I am trying to configure ReadFile to run asynchronously and according to MSDN , I need to set lpNumberOfBytesRead to null :

"Use NULL for this parameter if it is an asynchronous operation to avoid potentially erroneous results."

For example, if I have the following:

  [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern bool ReadFile( IntPtr hFile, out byte[] aBuffer, int cbToRead, IntPtr cbThatWereRead, ref OVERLAPPED pOverlapped ); 

and I call it that (with the intention of having a 4th parameter equal to zero):

 Win32API.ReadFile(readHandle, out data_read, Win32API.BUFFER_SIZE, IntPtr.Zero, ref over_lapped); 

would it be the same as calling it with a null value? If not, what should I change in the declaration or in the function call itself?

I was also curious whether to use SafeHandle or HandleRef instead of IntPtr for hFile reference? I know, to make sure I close the handle with CloseHandle(IntPtr) , when I am done with this, I’m just not sure if there is a reason to use the other two options over IntPtr . I also try to avoid using unsafe code.

EDIT: As it turned out, I did not have to set the fourth parameter in IntPtr.Zero anyway, because although I work asynchronously, it can still return immediately. See Asynchronous Disk I / O. Ah, I love conflicting stories.

+47
c # asynchronous file-io
Sep 21 '09 at 21:07
source share
3 answers

For P / Invoke purposes, as you pointed out, you should use IntPtr.Zero instead of NULL . Note that this is not equivalent to the C # NULL keyword.

+59
Sep 21 '09 at 21:11
source share

You cannot assign null to a value. The reference type can be null, as in, not refer to an instance of the object, but the value type always matters.

IntPtr.Zero is just a constant value that represents a null pointer.

+6
Sep 21 '09 at 21:56
source share

Remember that in C #> = 2.0 there is an error (function?), Where

 if (IntPtr.Zero == null) { // Won't enter here } 

will compile correctly, but it will never go into if .

An error appears on Microsoft connect, but it is quite old and there are no comments from Microsoft employees.

+6
Nov 03 '11 at 11:13
source share



All Articles