Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
666 views
in Technique[技术] by (71.8m points)

c# - Is IntPtr.Zero equivalent to null?

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

"Use NULL for this parameter if this 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 like this (with the intention of having the 4th parameter being null):

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

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

I was also curious if I should be using SafeHandle or HandleRef instead of IntPtr for the hFile reference? I know to make sure that I close the handle with CloseHandle(IntPtr) when I'm done with it, just not sure if there is any othe reason to use the other two options over IntPtr. I am also tryingn to avoid using unsafe code.

EDIT: As it turns out, I shouldnt be setting the fourth parameter to IntPtr.Zero anyway, because even though I am running asynchronously, it could still return right away. See Asynchronous Disk I/O. Ahh, I love contradicting stories.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For P/Invoke purposes like you've listed, you should use IntPtr.Zero in place of NULL. Note that this is not equivalent to the C# null keyword, however.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...