0

这是我的问题:如何遍历 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....

    }
4

1 回答 1

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;
        }
    }
}
于 2013-04-30T13:09:16.220 回答