我想保留在功能void ManipulateImagePixelData(CGImageRef inImage)
中分配的内存块(有关完整代码,请参见http://developer.apple.com/library/mac/#qa/qa1509/_index.html)
void ManipulateImagePixelData(CGImageRef inImage)
{
// Create the bitmap context
CGContextRef cgctx = CreateARGBBitmapContext(inImage);
if (cgctx == NULL)
{
// error creating context
return;
}
// Get image width, height. We'll use the entire image.
size_t w = CGImageGetWidth(inImage);
size_t h = CGImageGetHeight(inImage);
CGRect rect = {{0,0},{w,h}};
// Draw the image to the bitmap context. Once we draw, the memory
// allocated for the context for rendering will then contain the
// raw image data in the specified color space.
CGContextDrawImage(cgctx, rect, inImage);
// Now we can get a pointer to the image data associated with the bitmap
// context.
void *data = CGBitmapContextGetData (cgctx);
if (data != NULL)
{
// **** You have a pointer to the image data ****
// **** Do stuff with the data here ****
}
// When finished, release the context
CGContextRelease(cgctx);
// Free image data memory for the context
if (data)
{
free(data);
}
}
我已经修改了函数,以便具有宽度和高度,但是我无法设法获得
data
指向的存储块。我的功能看起来像:
void ManipulateImagePixelData(CGImageRef inImage,
unsigned long * width, unsigned long * height, void * copy)
最后,我不再释放数据,而是承担以后释放数据的责任。
我以为我可以做些简单的事情:
(caller)
void * rawPixels=NULL;
ManipulateImagePixelData([obj CGImageForProposedRect:NULL context:[NSGraphicsContext currentContext] hints:nil],&imgWidth1, &imgHeight1, rawPixels)];
(ManipulateImagePixelData function)
void * pixels = CGBitmapContextGetData (cgctx);
if (pixels != NULL) {
*width=w;
*height=h;
copy=pixels;
[...]
并且让rawPixels指向上述块,但是
rawPixels
在此调用之后仍然为NULL。我对此有些困惑,我的C技能也有些生锈。我应该怎么做才能获取数据?
最佳答案
您应该将指向变量的指针传递到ManipulateImagePixelData
中,您要在该变量中获取函数内分配的缓冲区的地址:
void ManipulateImagePixelData(CGImageRef inImage, unsigned long * width, unsigned long * height, void ** copy) {
...
void* data = CGBitmapContextGetData (cgctx);
*copy = data; // copy the output parameter
...
}
并这样称呼它:
void * rawPixels=NULL;
ManipulateImagePixelData([obj CGImageForProposedRect:NULL context:[NSGraphicsContext currentContext] hints:nil],&imgWidth1, &imgHeight1, &rawPixels)];
更好的是,您可以这样定义它:
void* ManipulateImagePixelData(CGImageRef inImage, unsigned long * width, unsigned long * height) {
...
void* data = CGBitmapContextGetData (cgctx);
...
return data;
}
关于objective-c - 如何使该指针保存在函数中分配的数据地址?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12986856/