日期:2014-05-18  浏览次数:21091 次

c#指针exp~
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace CSharp指针
{
  class Tester
  {
  static void Main(string[] args)
  {
   
  APIFileReader fileReader = new APIFileReader("myTestFile.txt");

  const int BuffSize = 128;
  byte[] buffer = new byte[BuffSize];
  ASCIIEncoding asciiEncoder = new ASCIIEncoding();

  while (fileReader.Read(buffer, 0, BuffSize) != 0)
  {
  Console.WriteLine("{0}",asciiEncoder.GetString(buffer));
  }
  Console.ReadKey();
  }
  }

  class APIFileReader
  {
  const uint GenericRead = 0x80000000;
  const uint OpenExisting = 3;
  const uint UseDefault = 0;
  int fileHandle;

  [DllImport("kernel32", SetLastError = true)]
  static extern unsafe int CreateFile(
  string filename,
  uint desiredAccess,
  uint shareMode,
  uint attributes,
  uint creationDisposition,
  uint flagsAndAttributes,
  uint templateFile);

  [DllImport("kernel32", SetLastError = true)]
  static extern unsafe bool ReadFile(
  int hFile,
  void* lpBuffer,
  int nBytesToRead,
  int* nBytesRead,
  int overlapped
  );

  //类APIFileReader的构造函数打开要读取的文件,并将运行结果赋值给成员函数fileHandle
  public APIFileReader(string filename)
  {
  fileHandle = CreateFile(
  filename,
  GenericRead,
  UseDefault,
  UseDefault,
  OpenExisting,
  UseDefault,
  UseDefault);
  }

  public unsafe int Read(byte[] buffer, int index, int count)
  {
  int bytesRead = 0;
  fixed (byte* bytesPointer = buffer)
  {
  ReadFile(
  fileHandle,
  bytesPointer + index,
  count,
  &bytesRead,
  0);
  }
  return bytesRead;
  }
  }
}

因为WIndowsAPI的ReadFile函数的第2个参数是指针,所以要用到指针~~~~~

------解决方案--------------------
//1

[DllImport("kernel32.dll")]
static extern bool ReadFile(IntPtr hFile, byte[] lpBuffer,
uint nNumberOfBytesToRead, out uint lpNumberOfBytesRead, IntPtr lpOverlapped);

or

//2

[DllImport("kernel32.dll", SetLastError=true)]
static extern unsafe int ReadFile(IntPtr handle, IntPtr bytes, uint numBytesToRead,
IntPtr numBytesRead, NativeOverlapped* overlapped);

or

//3

[DllImport("kernel32.dll", SetLastError=true)]
static extern bool ReadFile(IntPtr hFile, [Out] byte[] lpBuffer, uint nNumberOfBytesToRead,
out uint lpNumberOfBytesRead, [In] ref System.Threading.NativeOverlapped lpOverlapped);

or

//4

[DllImport("kernel32.dll"