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