通过IntPtr循环

looping through IntPtr?

本文关键字:循环 IntPtr 通过      更新时间:2023-10-16

这是我的问题:我如何循环通过一个IntPtr在c#中指向的东西?我有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:ProjectsImageStatisticsImageStatisticsEllipseDebugDiskIO.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....
    }

这是如何循环使用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;
        }
    }
}