循环通过IntPtr?

时间:2013-03-21 14:50:39

标签: c# c++ intptr

以下是我的问题:如何在C#中循环使用IntPtr指向的内容? 我有C#代码调用C ++代码。 C ++代码返回指向一段图像缓冲区的指针。 C#和C ++之间的接口是在C#中声明的IntPtr变量 所以这是我的C#代码:

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);

这是我的C ++代码:

DllExport_ThorDiskIO ReadImage(char *selectedFileName, char* &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->TIFFOpenW(path, "r")) == NULL){
        //      logDll->TLTraceEvent(VERBOSE_EVENT,1,L"Could not open incoming image");

    }

    // Read in the possibly multiple strips
    stripSize = tiffDll->TIFFStripSize(image);
    stripMax = tiffDll->TIFFNumberOfStrips (image);
    imageOffset = 0;

    bufferSize = tiffDll->TIFFNumberOfStrips (image) * stripSize;

    for (stripCount = 0; stripCount < stripMax; stripCount++)
    {
        if((result = tiffDll->TIFFReadEncodedStrip (image, stripCount, outputBuffer + imageOffset, stripSize)) == -1)
        {
            //logDll->TLTraceEvent(VERBOSE_EVENT,1,L"Read error on input strip number");
        }
        imageOffset += result;
    }

    // Close the TIFF image
    tiffDll->TIFFClose(image);

    if(outputBuffer > 0)
    {
        //logDll->TLTraceEvent(VERBOSE_EVENT,1,L"inside output buffer: TRUE");
        status = TRUE;
    }
    else
    {
        //logDll->TLTraceEvent(VERBOSE_EVENT,1,L"inside output buffer: FALSE");
        status = FALSE;
    }   
    return status;  
}

所以现在我认为我可以成功获得IntPtr,但问题是:我如何使用它?如何遍历图像缓冲区中的每个像素,如(伪代码):

for (int y = 0; y < imgHeight; y++)
    for (int x = 0; x < imgWidth; x++)
    {
        int pixVal = IntPtr[y * imgWidth + x ];

        // do something to process the pixel value here....

    }

1 个答案:

答案 0 :(得分:2)

这是如何遍历使用IntPtr指向的图像(指向本机内存的指针)

//assume this actually points to something (not zero!!)
IntPtr pNative = IntPtr.Zero;

//assume these are you image dimensions
int w=640; //width
int h=480; //height
int ch =3; //channels

//image loop
//use unsafe
//this is very fast!! 
unsafe
{
    for (int r = 0; r < h; r++)
    {
        byte* pI = (byte*)pNative.ToPointer() + r*w*ch; //pointer to start of row
        for (int c = 0; c < w; c++)
        {
            pI[c * ch]      = 0; //red
            pI[c * ch+1]    = 0; //green
            pI[c * ch+2]    = 0; //blue

//also equivalent to *(pI + c*ch)  = 0 - i.e. using pointer arythmetic;
        }
    }
}