2013-12-19 56 views
-1

我只想知道我们可以在C#中使用指针。我们可以访问C#中的指针吗?

我们可以在C++中使用指针,但我不知道我们可以在C#中使用它们。

我也想知道是否有任何指针用于非托管代码。

+6

您可以访问'unsafe'上下文中的指针。否则,你不会:语言遮掩它。 –

+2

你很少(如果有的话)在C#中使用指针。 请参阅http://stackoverflow.com/questions/5171781/when-to-use-pointers-in-c-net – mason

+2

你为什么要访问指针?你想要达到什么目标,你不能没有指针? –

回答

3

是的,你可以使用指针。 See unsafe keyword

一个使用之实践的一个例子:图像转换为灰度

public static Bitmap MakeGrayscale2(Bitmap original) 
{ 
    unsafe 
    { 
     //create an empty bitmap the same size as original 
     Bitmap newBitmap = new Bitmap(original.Width, original.Height); 

     //lock the original bitmap in memory 
     BitmapData originalData = original.LockBits(
     new Rectangle(0, 0, original.Width, original.Height), 
     ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); 

     //lock the new bitmap in memory 
     BitmapData newData = newBitmap.LockBits(
     new Rectangle(0, 0, original.Width, original.Height), 
     ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb); 

     //set the number of bytes per pixel 
     int pixelSize = 3; 

     for (int y = 0; y < original.Height; y++) 
     { 
     //get the data from the original image 
     byte* oRow = (byte*)originalData.Scan0 + (y * originalData.Stride); 

     //get the data from the new image 
     byte* nRow = (byte*)newData.Scan0 + (y * newData.Stride); 

     for (int x = 0; x < original.Width; x++) 
     { 
      //create the grayscale version 
      byte grayScale = 
       (byte)((oRow[x * pixelSize] * .11) + //B 
       (oRow[x * pixelSize + 1] * .59) + //G 
       (oRow[x * pixelSize + 2] * .3)); //R 

      //set the new image's pixel to the grayscale version 
      nRow[x * pixelSize] = grayScale; //B 
      nRow[x * pixelSize + 1] = grayScale; //G 
      nRow[x * pixelSize + 2] = grayScale; //R 
     } 
     } 

     //unlock the bitmaps 
     newBitmap.UnlockBits(newData); 
     original.UnlockBits(originalData); 

     return newBitmap; 
    } 
} 

As seen here

+0

谢谢,非常好的dicription –

相关问题