title: looping through IntPtr?
body: <p>Here is my question: <strong>How do I loop through the stuff pointed by an IntPtr in C#?</strong>
  I have C# code calling C++ code. The C++ code returns a pointer to a piece of image buffer. The interface between C# and C++ is an IntPtr variable declared in C#
  So here is my C# code:</p>
  
  <pre><code>private IntPtr _maskData;
  
  public void LoadMask(string maskName)
  {            
       _maskData = Marshal.AllocHGlobal(_imgWidth * _imgHeight * 1);
       ReadImage(maskName, ref _maskData);
  }
  
  [DllImport(@"D:\Projects\ImageStatistics\ImageStatisticsEllipse\Debug\DiskIO.dll", EntryPoint = "ReadImage")]
          private static extern int ReadImage([MarshalAs(UnmanagedType.LPWStr)]string path, ref IntPtr outputBuffer);
  </code></pre>
  
  <p>Here is my C++ code:</p>
  
  <pre><code>DllExport_ThorDiskIO ReadImage(char *selectedFileName, char* &amp;outputBuffer)
  {
      TIFF* image;
      tsize_t stripSize;
      unsigned long imageOffset, result;
      int stripMax, stripCount;
      unsigned long bufferSize;
      wchar_t * path = (wchar_t*)selectedFileName;
      bool status;
  
      // Open the TIFF image
      if((image = tiffDll-&gt;TIFFOpenW(path, "r")) == NULL){
          //      logDll-&gt;TLTraceEvent(VERBOSE_EVENT,1,L"Could not open incoming image");
  
      }
  
      // Read in the possibly multiple strips
      stripSize = tiffDll-&gt;TIFFStripSize(image);
      stripMax = tiffDll-&gt;TIFFNumberOfStrips (image);
      imageOffset = 0;
  
      bufferSize = tiffDll-&gt;TIFFNumberOfStrips (image) * stripSize;
  
      for (stripCount = 0; stripCount &lt; stripMax; stripCount++)
      {
          if((result = tiffDll-&gt;TIFFReadEncodedStrip (image, stripCount, outputBuffer + imageOffset, stripSize)) == -1)
          {
              //logDll-&gt;TLTraceEvent(VERBOSE_EVENT,1,L"Read error on input strip number");
          }
          imageOffset += result;
      }
  
      // Close the TIFF image
      tiffDll-&gt;TIFFClose(image);
  
      if(outputBuffer &gt; 0)
      {
          //logDll-&gt;TLTraceEvent(VERBOSE_EVENT,1,L"inside output buffer: TRUE");
          status = TRUE;
      }
      else
      {
          //logDll-&gt;TLTraceEvent(VERBOSE_EVENT,1,L"inside output buffer: FALSE");
          status = FALSE;
      }   
      return status;  
  }
  </code></pre>
  
  <p>So right now I think I can get the IntPtr successfully, but the question really is: How do I use it? How do I loop through each pixel in the image buffer, something like (pseudo code):</p>
  
  <pre><code>for (int y = 0; y &lt; imgHeight; y++)
      for (int x = 0; x &lt; imgWidth; x++)
      {
          int pixVal = IntPtr[y * imgWidth + x ];
  
          // do something to process the pixel value here....
  
      }
  </code></pre>