问题描述
Sir:IhookReadFileasfollowing:[System.Runtime.InteropServices.DllImport("kernel32")]publicstaticexternboolReadFile(IntPtrhFile,byte[]lpBuffer,uintnNumberOfBytesToRead,refuintlpNumberOfBytesRead,IntPtrlpOverlapped);//myhookfunctionboolMyReadFile(IntPtrhFile,byte[]lpBuffer,uintnNumberOfBytesToRead,refuintlpNumberOfBytesRead,IntPtrlpOverlapped){}whenprogrampassMyReadFile(),thelengthoflpBufferisonly1,butthevalueofnNumberOfBytesToReadis4096,why?thankswei_future@sina.com
解决方案
解决方案二:
MARKhavn’tincvokeReadFilefunction
解决方案三:
下面的示例通过读取并显示一个文本文件来演示WindowsReadFile函数。ReadFile函数需要使用unsafe代码,因为它需要一个作为参数的指针。传递到Read函数的字节数组是托管类型。这意味着公共语言运行库(CLR)垃圾回收器可能会随意地对数组使用的内存进行重新定位。为了防止出现这种情况,使用fixed来获取指向内存的指针并对它进行标记,以便垃圾回收器不会移动它。在fixed块的末尾,内存将自动返回,以便能够通过垃圾回收移动。此功能称为“声明式锁定”。锁定的好处是系统开销非常小,除非在fixed块中发生垃圾回收(但此情况不太可能发生)。classFileReader{constuintGENERIC_READ=0x80000000;constuintOPEN_EXISTING=3;System.IntPtrhandle;[System.Runtime.InteropServices.DllImport("kernel32",SetLastError=true)]staticexternunsafeSystem.IntPtrCreateFile(stringFileName,//filenameuintDesiredAccess,//accessmodeuintShareMode,//sharemodeuintSecurityAttributes,//SecurityAttributesuintCreationDisposition,//howtocreateuintFlagsAndAttributes,//fileattributesinthTemplateFile//handletotemplatefile);[System.Runtime.InteropServices.DllImport("kernel32",SetLastError=true)]staticexternunsafeboolReadFile(System.IntPtrhFile,//handletofilevoid*pBuffer,//databufferintNumberOfBytesToRead,//numberofbytestoreadint*pNumberOfBytesRead,//numberofbytesreadintOverlapped//overlappedbuffer);[System.Runtime.InteropServices.DllImport("kernel32",SetLastError=true)]staticexternunsafeboolCloseHandle(System.IntPtrhObject//handletoobject);publicboolOpen(stringFileName){//opentheexistingfileforreadinghandle=CreateFile(FileName,GENERIC_READ,0,0,OPEN_EXISTING,0,0);if(handle!=System.IntPtr.Zero){returntrue;}else{returnfalse;}}publicunsafeintRead(byte[]buffer,intindex,intcount){intn=0;fixed(byte*p=buffer){if(!ReadFile(handle,p+index,count,&n,0)){return0;}}returnn;}publicboolClose(){returnCloseHandle(handle);}}classTest{staticintMain(string[]args){if(args.Length!=1){System.Console.WriteLine("Usage:ReadFile<FileName>");return1;}if(!System.IO.File.Exists(args[0])){System.Console.WriteLine("File"+args[0]+"notfound.");return1;}byte[]buffer=newbyte[128];FileReaderfr=newFileReader();if(fr.Open(args[0])){//AssumethatanASCIIfileisbeingread.System.Text.ASCIIEncodingEncoding=newSystem.Text.ASCIIEncoding();intbytesRead;do{bytesRead=fr.Read(buffer,0,buffer.Length);stringcontent=Encoding.GetString(buffer,0,bytesRead);System.Console.Write("{0}",content);}while(bytesRead>0);fr.Close();return0;}else{System.Console.WriteLine("Failedtoopenrequestedfile");return1;}}}
解决方案四:
什么情况?